Intersection |
Time Limit: 1000ms, Special Time Limit:2500ms, Memory Limit:32768KB |
Problem 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) 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 |
1 4 9 11 2 1 5 7 1 |
Sample Output |
F |
Judge Tips |
注意看题目说明,top的值可能会小于bottom. 线段在矩形里面也算相交. |
///// WA了三次,存到博客上以供查询。思路,相看线段所在直线是否与矩形相交,如果不相交则必为 “F”,如果相交,则看线段的两个点是否在矩形的同一边(即两点的 x(y) 坐标都比矩形的小 x(y) 坐标小,或者大),若在同一边则为“F”,否则就是相交的情况。
//// my code
#include <iostream>
using namespace std;
int main(){
int n,xs,ys,xe,ye,xleft,ytop,xr,yb;
cin>>n;
for(int i=0; i<n; i++){
cin>>xs>>ys>>xe>>ye>>xleft>>ytop>>xr>>yb;
int a=ys-ye, b=xe-xs, c=xs*ye-xe*ys;
if( (a*xleft+b*ytop+c>=0 && a*xr+b*yb+c<=0)||
(a*xleft+b*ytop+c<=0 && a*xr+b*yb+c>=0)||
(a*xleft+b*yb+c>=0 && a*xr+b*ytop+c<=0)||
(a*xleft+b*yb+c<=0 && a*xr+b*ytop+c>=0) ){
if(xleft > xr)
swap(xleft,xr);
if(ytop < yb)
swap(ytop,yb);
if( (xs<xleft && xe<xleft) ||
(xs>xr && xe>xr) ||
(ys>ytop && ye>ytop) ||
(ys<yb && ye<yb) )
cout<<"F"<<endl;
else
cout<<"T"<<endl;
}
else
cout<<"F"<<endl;
}
return 0;
}
评论