欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Intersecting Lines POJ - 1269

程序员文章站 2022-04-02 18:17:32
...
#include <cmath>
#include <cstdio>
using namespace std;
/*
判断直线是否相交或者共线,并求出交点
*/

const double ESP = 1e-10;
int dcmp(double x) {
    if (fabs(x) < ESP) {
        return 0;
    } else {
        return x < 0 ? -1 : 1;
    }
}
//点
struct Point {
    double x, y;
    Point(double x = 0, double y = 0) : x(x), y(y) {}
};

//向量
typedef Point Vector;

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 k) {
    return Vector(A.x * k, A.y * k);
}

Vector operator/(Vector A, double k) {
    return Vector(A.x / k, A.y / k);
}

bool operator<(const Point &A, const Point &B) {
    return A.x < B.x || (A.x == B.x && A.y < B.y);
}

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 Cross(Vector A, Vector B) {
    return A.x * B.y - A.y * B.x;
}

//一个点是否在直线上
bool OnLine(Point A, Point B, Point P) {
    return dcmp(Cross(A - P, B - P)) == 0;
}

//两直线平行
bool isLineParallel(Point A, Point B, Point C, Point D) {
    return dcmp(Cross(A - B, C - D)) == 0 && !OnLine(A, B, C);
}

//两直线共线
bool isLineCommon(Point A, Point B, Point C, Point D) {
    return dcmp(Cross(A - B, C - D)) == 0 && OnLine(A, B, C);
}

//两直线交点
Point GetLineIntersection(Point P, Vector v, Point Q, Vector w) {
    Vector u = P - Q;
    double t = Cross(w, u) / Cross(v, w);
    return P + v * t;
}

const int MAXN = 100 + 5;
Point points[MAXN];
int n;

void slove() {
    printf("INTERSECTING LINES OUTPUT\n");

    for (int i = 0; i < n - 1; i += 4) {
        if (isLineCommon(points[i], points[i + 1], points[i + 2], points[i + 3])) {
            printf("LINE\n");
        } else if (isLineParallel(points[i], points[i + 1], points[i + 2], points[i + 3])) {
            printf("NONE\n");
        } else {
            Point ans = GetLineIntersection(points[i], points[i + 1] - points[i], points[i + 2], points[i + 3] - points[i + 2]);
            printf("POINT %.2lf %.2lf\n", ans.x, ans.y);//g++有毒.2f可以过.2lf过不了,或者用c++
        }
    }
    printf("END OF OUTPUT\n");
}

int main() {
    scanf("%d", &n);
    n *= 4;
    for (int i = 0; i < n; i += 4) {
        scanf("%lf%lf%lf%lf%lf%lf%lf%lf", &points[i].x, &points[i].y, &points[i + 1].x, &points[i + 1].y,
              &points[i + 2].x, &points[i + 2].y, &points[i + 3].x, &points[i + 3].y);
    }
    slove();
    return 0;
}

相关标签: 计算几何