题目描述
传送门
题意:给出一条线段和一个矩形,判断它们是否有公共点
题解
先判断线段和矩形的每一条边是否相交
然后再判断线段是否在矩形内部
由于是一个简单的矩形不是多边形只需要判断坐标范围就行了
矩形的坐标给出的是无序的,需要自己排序
代码
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
using namespace std;
const double eps=1e-9;
int dcmp(double x)
{
if (x<=eps&&x>=-eps) return 0;
return (x>0)?1:-1;
}
struct Vector
{
double x,y;
Vector(double X=0,double Y=0)
{
x=X,y=Y;
}
};
typedef Vector Point;
struct Line
{
Point p,q;
Line(Point P=Point(0,0),Point Q=Point(0,0))
{
p=P,q=Q;
}
};
Vector operator - (Vector A,Vector B) {return Vector(A.x-B.x,A.y-B.y);}
int T;
Point A,B;
Line l,m;
double a,b,c,d;
bool flag;
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 check(Line l,Line m)
{
bool flag=true;
Vector u,v,w;
int x,y;
u=l.p-l.q;v=m.p-l.q;w=m.q-l.q;
x=dcmp(Cross(u,v));y=dcmp(Cross(u,w));
if ((x==y&&x)||(!x&&!y&&dcmp(Dot(v,w))>=0)) flag=false;
u=m.p-m.q;v=l.p-m.q;w=l.q-m.q;
x=dcmp(Cross(u,v));y=dcmp(Cross(u,w));
if ((x==y&&x)||(!x&&!y&&dcmp(Dot(v,w))>=0)) flag=false;
return flag;
}
bool PInP(Point P,double a,double b,double c,double d)
{
return dcmp(P.x-a)>=0&&dcmp(P.x-c)<=0&&dcmp(P.y-b)>=0&&dcmp(P.y-d)<=0;
}
int main()
{
scanf("%d",&T);
while (T--)
{
flag=false;
scanf("%lf%lf%lf%lf",&a,&b,&c,&d);
A=Point(a,b),B=Point(c,d);
l=Line(A,B);
scanf("%lf%lf%lf%lf",&a,&b,&c,&d);
if (dcmp(a-c)>0) swap(a,c);
if (dcmp(b-d)>0) swap(b,d);
m=Line(Point(a,b),Point(a,d));
flag|=check(l,m);
m=Line(Point(a,b),Point(c,b));
flag|=check(l,m);
m=Line(Point(c,d),Point(a,d));
flag|=check(l,m);
m=Line(Point(c,d),Point(c,b));
flag|=check(l,m);
if (flag) puts("T");
else
{
if (PInP(A,a,b,c,d)&&PInP(B,a,b,c,d)) puts("T");
else puts("F");
}
}
}