题目大意:
给定一个矩形和一个线段,问矩形与线段是否存在公共点(矩形包括四条边和四条边所围成的部分)。
一个矩形与一个线段相交当且仅当:
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;
}