【计算几何】POJ 1410

题目大意:
给定一个矩形和一个线段,问矩形与线段是否存在公共点(矩形包括四条边和四条边所围成的部分)。

一个矩形与一个线段相交当且仅当:
1.线段的一个端点在矩形内或矩形上
2.线段与矩形的某条边相交
两部分分别判断一下就可以了。

附上AC代码:

#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <algorithm>

using namespace std;

class Point
{
    public:
        double x, y;
        Point(double x = 0, double y = 0): x(x), y(y) {}
};

typedef Point Vector;

Vector operator + (const Vector &a, const Vector &b)
{
    return Vector(a.x+b.x, a.y+b.y);
}

Vector operator - (const Point &a, const Point &b)
{
    return Vector(a.x-b.x, a.y-b.y);
}

Vector operator * (const Vector &a, const double &b)
{
    return Vector(a.x*b, a.y*b);
}

Vector operator / (const Vector &a, const double &b)
{
    return Vector(a.x/b, a.y/b);
}

double Dot(const Vector &a, const Vector &b)
{
    return a.x*b.x + a.y*b.y;
}

double Cross(const Vector &a, const Vector &b)
{
    return a.x*b.y - a.y*b.x;
}

Point LineIntersection(Point p, Vector v, Point q, Vector w)
{
    Vector u = p-q;
    double t = Cross(w, u) / Cross(v, w);
    return p + v*t;
}

bool onLine(Point a, Point b, Point p)
{
    return ((a.x <= p.x && p.x <= b.x) || (b.x <= p.x && p.x <= a.x))
        && ((a.y <= p.y && p.y <= b.y) || (b.y <= p.y && p.y <= a.y));
}

bool check(Point a, Point b, Point c, Point d)
{
    Point cp = LineIntersection(a, b-a, c, d-c);
    return onLine(a, b, cp) && onLine(c, d, cp);
}

bool inRectangle(double xl, double xr, double yl, double yr, Point a, Point b)
{
    return (a.x >= xl && a.x <= xr && a.y >= yl && a.y <= yr) 
        || (b.x >= xl && b.x <= xr && b.y >= yl && b.y <= yr);
}

int main()
{
    int t;
    double x1, x2, y1, y2, px1, py1, px2, py2;
    scanf("%d", &t);
    while (t--) {
        scanf("%lf %lf %lf %lf %lf %lf %lf %lf", &px1, &py1, &px2, &py2, &x1, &y1, &x2, &y2);
        if (x1 > x2)
            swap(x1, x2);
        if (y1 > y2)
            swap(y1, y2);
        Point lp1(px1, py1), lp2(px2, py2);
        if (inRectangle(x1, x2, y1, y2, lp1, lp2)) {
            printf("T\n");
            continue;
        }
        if (check(Point(x1, y1), Point(x1, y2), lp1, lp2)) {
            printf("T\n");
            continue;
        }
        if (check(Point(x1, y1), Point(x2, y1), lp1, lp2)) {
            printf("T\n");
            continue;
        }
        if (check(Point(x1, y2), Point(x2, y2), lp1, lp2)) {
            printf("T\n");
            continue;
        }
        if (check(Point(x2, y1), Point(x2, y2), lp1, lp2)) {
            printf("T\n");
            continue;
        }
        printf("F\n");
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值