poj1410 簡單計算幾何


題目鏈接:http://poj.org/problem?id=1410

題意:判斷一條線段與一個矩形(四條邊以及中間包含的部分)是否相交

思路:線段是否與四條邊非規范相交,線段在矩形內部且與任一邊不相交

#include <iostream>
#include <cstdio>
#include <cmath>
using namespace std;

const double eps = 1e-8;

struct Point {
    double x, y;
};

double Max(double a, double b) {
    return a > b ? a : b;
}

double Min(double a, double b) {
    return a > b ? b : a;
}

double Multi(Point p1, Point p2, Point p0) {
    return (p1.x-p0.x)*(p2.y-p0.y)-(p1.y-p0.y)*(p2.x-p0.x);
}

int dblcmp(double m) {
    if (fabs(m) < eps) return 0;
    return m > 0 ? 1 : -1;
}

//注意處理非規范相交,例如與邊的端點相交,或與邊共線相交的情況
bool Cross(Point a, Point b, Point c, Point d) {
    if (dblcmp(Max(a.x, b.x)-Min(c.x, d.x)) >= 0 && dblcmp(Max(c.x, d.x)-Min(a.x, b.x)) >= 0
        && dblcmp(Max(a.y, b.y)-Min(c.y, d.y)) >= 0 && dblcmp(Max(c.y, d.y)-Min(a.y, b.y)) >= 0
        && dblcmp(Multi(a, d, c)*Multi(b, d, c)) <= 0 && dblcmp(Multi(c, b, a)*Multi(d, b, a)) <= 0)
                return true;
    return false;
}

int main()
{
    int n;
    double x1, x2, y1, y2, xl, xr, yup, ydown;
    Point a, b, p1, p2, p3, p4;
    bool flag;
    scanf ("%d", &n);
    while (n--) {
         scanf ("%lf%lf%lf%lf%lf%lf%lf%lf", &a.x, &a.y, &b.x, &b.y, &x1, &y1, &x2, &y2);
         xl = Min(x1, x2);
         xr = Max(x1, x2);
         yup = Max(y1, y2);
         ydown = Min(y1, y2);
         flag = false;
         if (Max(a.x, b.x) < xr && Max(a.y, b.y) < yup && Min(a.x, b.x) > xl && Min(a.y, b.y) > ydown)
            flag = true;
         else {
            p1.x = p2.x = xl;
            p1.y = p4.y = ydown;
            p2.y = p3.y = yup;
            p3.x = p4.x = xr;
            if (Cross(a, b, p1, p2) || Cross(a, b, p2, p3) || Cross(a, b, p3, p4) || Cross(a, b, p4, p1))
                flag = true;
         }
         if (flag) printf ("T\n");
         else printf ("F\n");
    }
    return 0;
}



注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2020 ITdaan.com