Language: Intersection
Description You are to write a program that has to decide whether a given line segment intersects a given rectangle. Input The input consists of n test cases. The first line of the input file contains the number n. Each following line contains one test case of the format: Output For each test case in the input file, the output file should contain a line consisting either of the letter "T" if the line segment intersects the rectangle or the letter "F" if the line segment does not intersect the rectangle. Sample Input 14 9 11 2 1 5 7 1 Sample Output F
|
题意:判断一条线段是否和矩形相交;
想到了直线可能完全在矩形内部但却没有完全理解题意The terms top left and bottom right do not imply any ordering of coordinates;注意它们的位置关系不确定
#include<cstdio>
#include<cstdlib>
#include<cstring>
#define eps 1e-8
using namespace std;
struct point{
double x,y;
};
struct line{
point a,b;
}A[100010];
double MAX(double a,double b){
return a>b?a:b;
}
double MIN(double a,double b){
return a<b?a:b;
}
bool judge(int a,int b){
if(MIN(A[a].a.x,A[a].b.x)>MAX(A[b].a.x,A[b].b.x)||MIN(A[a].a.y,A[a].b.y)>MAX(A[b].a.y,A[b].b.y)||MIN(A[b].a.x,A[b].b.x)>MAX(A[a].a.x,A[a].b.x)||MIN(A[b].a.y,A[b].b.y)>MAX(A[a].a.y,A[a].b.y))
return false;
double h,i,j,k;
h=(A[a].b.x-A[a].a.x)*(A[b].a.y-A[a].a.y)-(A[a].b.y-A[a].a.y)*(A[b].a.x-A[a].a.x);
i=(A[a].b.x-A[a].a.x)*(A[b].b.y-A[a].a.y)-(A[a].b.y-A[a].a.y)*(A[b].b.x-A[a].a.x);
j=(A[b].b.x-A[b].a.x)*(A[a].a.y-A[b].a.y)-(A[b].b.y-A[b].a.y)*(A[a].a.x-A[b].a.x);
k=(A[b].b.x-A[b].a.x)*(A[a].b.y-A[b].a.y)-(A[b].b.y-A[b].a.y)*(A[a].b.x-A[b].a.x);
return h*i<=eps&&j*k<=eps;
}
int main()
{
int t,i,j,k;
double xleft,ytop,xright,ybottom;
double x1,y1,x2,y2;
scanf("%d",&t);
while(t--){
scanf("%lf%lf%lf%lf",&A[0].a.x,&A[0].a.y,&A[0].b.x,&A[0].b.y);
scanf("%lf%lf%lf%lf",&x1,&y1,&x2,&y2);
xleft=MIN(x1,x2);xright=MAX(x1,x2);
ybottom=MIN(y1,y2);ytop=MAX(y1,y2);
A[1].a.x=xleft;A[1].a.y=ybottom;A[1].b.x=xleft;A[1].b.y=ytop;
A[2].a.x=xleft;A[2].a.y=ytop;A[2].b.x=xright;A[2].b.y=ytop;
A[3].a.x=xright;A[3].a.y=ytop;A[3].b.x=xright;A[3].b.y=ybottom;
A[4].a.x=xright;A[4].a.y=ybottom;A[4].b.x=xleft;A[4].b.y=ybottom;
for(i=1;i<=4;++i){
if(judge(0,i))break;
}
bool flag=false;
if(A[0].a.x<=xright&&A[0].a.x>=xleft&&A[0].a.y>=ybottom&&A[0].a.y<=ytop)flag=true;
if(A[0].b.x<=xright&&A[0].b.x>=xleft&&A[0].b.y>=ybottom&&A[0].b.y<=ytop)flag=true;
if(i>4&&flag==0)
printf("F\n");
else
printf("T\n");
}
return 0;
}