POJ 1410 Intersection(判断线段与矩形是否相交)

来源:互联网 发布:淘宝买硬盘 编辑:程序博客网 时间:2024/04/30 15:51
Intersection
Time Limit: 1000MS Memory Limit: 10000KTotal Submissions: 13106 Accepted: 3412

Description

You are to write a program that has to decide whether a given line segment intersects a given rectangle.

An example:
line: start point: (4,9)
end point: (11,2)
rectangle: left-top: (1,5)
right-bottom: (7,1)


Figure 1: Line segment does not intersect rectangle

The line is said to intersect the rectangle if the line and the rectangle have at least one point in common. The rectangle consists of four straight lines and the area in between. Although all input values are integer numbers, valid intersection points do not have to lay on the integer grid.

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:
xstart ystart xend yend xleft ytop xright ybottom

where (xstart, ystart) is the start and (xend, yend) the end point of the line and (xleft, ytop) the top left and (xright, ybottom) the bottom right corner of the rectangle. The eight numbers are separated by a blank. The terms top left and bottom right do not imply any ordering of coordinates.

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大意:给出一条线段的起点和终点,然后给出一个矩形的斜对角线的起点和终点,判断这条线段和这个矩形是否相交思路:将直线方程求出,为Ax+By+C=0,然后判断,如果与矩形相交,那么会有两个点分别在线段两侧,那么代入值会是一个正一个负。。但这不是唯一的判断,这条线段会存在于这个矩形中,也就是说这个矩形会包含这条线段,此时两个值也是一个正一个负,那么就要判断这条线段的两个端点和矩形四个顶点的关系就行了。ac代码:
#include<stdio.h>#include<math.h>#include<string.h>#include<iostream>#include<algorithm>#define MAXN 100010#define LL long longusing namespace std;struct s{int x;int y;}begin,end,sqb,sqe;int main(){int t,a,b,c;int num1,num2;scanf("%d",&t);while(t--){scanf("%d%d%d%d%d%d%d%d",&begin.x,&begin.y,&end.x,&end.y,&sqb.x,&sqb.y,&sqe.x,&sqe.y);a=begin.y-end.y;b=end.x-begin.x;c=end.y*begin.x-end.x*begin.y;if(sqb.x>sqe.x)//为了严谨,将顶点顺序保持前者为上{int x=sqb.x; sqb.x=sqe.x; sqe.x=x;}        if(sqb.y<sqe.y){int y=sqb.y; sqb.y=sqe.y; sqe.y=y;}num1=(a*sqb.x+b*sqb.y+c)*(a*sqe.x+b*sqe.y+c);num2=(a*sqb.x+b*sqe.y+c)*(a*sqe.x+b*sqb.y+c);if(num1>0&&num2>0){printf("F\n");continue;}if((begin.x<sqb.x&&end.x<sqb.x)||(begin.x>sqe.x&&end.x>sqe.x)||(begin.y>sqb.y&&end.y>sqb.y)||(begin.y<sqe.y&&end.y<sqe.y))//检查是否包含printf("F\n");elseprintf("T\n");}return 0;}


0 0
原创粉丝点击