首页 > 其他 > 详细

模板 - 计算几何 - 点

时间:2020-02-05 19:14:49      阅读:46      评论:0      收藏:0      [点我收藏+]

const double eps = 1e-9;
const double PI = acos(-1.0);

int sgn(double x) {
    return (abs(x) <= eps) ? 0 : (x > 0 ? 1 : -1);
}

struct Point {
    double x, y;
    Point() {}
    Point(double x, double y): x(x), y(y) {}

    double len() {
        return sqrt(x * x + y * y);
    }

    friend Point operator+(const Point &a, const Point &b) {
        return Point(a.x + b.x, a.y + b.y);
    }
    friend Point operator-(const Point &a, const Point &b) {
        return Point(a.x - b.x, a.y - b.y);
    }
    friend Point operator*(const Point &p, const double &k) {
        return Point(k * p.x, k * p.y);
    }
    friend Point operator*(const double &k, const Point &p) {
        return Point(k * p.x, k * p.y);
    }
    friend bool operator==(const Point &a, const Point &b) {
        return (sgn(a.x - b.x) == 0) && (sgn(a.y - b.y) == 0);
    }
    friend double operator*(const Point &a, const Point &b) {
        return a.x * b.x + a.y * b.y;
    }
    friend double operator^(const Point &a, const Point &b) {
        return a.x * b.y - a.y * b.x;
    }
    friend double dis(const Point &a, const Point &b) {
        return sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y));
    }

    //返回绕原点旋转A弧度的结果
    Point Rotate(const double &A) {
        return Point(x * cos(A) - y * sin(A), x * sin(A) + y * cos(A));
    }
};

线段/直线

struct Segment {
    Point s, t;
    Segment() {}
    Segment(const Point &s, const Point &t): s(s), t(t) {}

    //返回点到线段的距离
    double PointDistanceWithSegment(const Point &p) {
        if(sgn((p - s) * (t - s)) < 0)
            return (p - s).len();
        if(sgn((p - t) * (s - t)) < 0)
            return (p - t).len();
        return abs((s - p) ^ (t - p)) / dis(s, t);
    }

    //返回点到直线的投影
    Point PointProjectToLine(const Point &p) {
        double r = ((t - s) * (p - s)) / ((t - s) * (t - s));
        return s + r * (t - s);
    }

    //判断点是否在线段上
    bool PointOnSegment(const Point &p) {
        return (sgn((p - s) ^ (t - s)) == 0) && (sgn((p - s) * (p - t)) <= 0);
    }

    //判断两条直线是否平行
    bool LineParallelWithLine(const Segment &l) {
        return !sgn((s - t) ^ (l.s - l.t));
    }
};

模板 - 计算几何 - 点

原文:https://www.cnblogs.com/KisekiPurin2019/p/12264760.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!