原题传送门:http://poj.org/problem?id=1410
博主的中文题面(放心提交):
https://www.luogu.org/problemnew/show/T22919
Intersection
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
1
4 9 11 2 1 5 7 1
Sample Output
F
题目大意
判断线段和矩形是否相交
题解
枚举四条边计算交点,特判共线和在内部的情况
坑
线段在矩形内部也算相交,先输入线段再输入矩形,矩形的端点不是按顺序给的,只能保证倒数1、3个是横坐标,2、4个是纵坐标,共线的时候叉乘出来会WA,需要写个特判(即under函数)。
代码
#include<cstdio>
#include<algorithm>
#define db double
using namespace std;
const db eps=1e-8;
struct pt{db x,y;};
pt s,e,lu,ld,ru,rd;
int sig(db x){return (x>eps)-(x<-eps);}
db cross(pt a,pt b,pt c){return (b.x-a.x)*(c.y-a.y)-(b.y-a.y)*(c.x-a.x);}
void in()
{
scanf("%lf%lf%lf%lf%lf%lf%lf%lf",&s.x,&s.y,&e.x,&e.y,&lu.x,&lu.y,&rd.x,&rd.y);
if(lu.x>rd.x) swap(lu.x,rd.x);
if(lu.y<rd.y) swap(lu.y,rd.y);
ld.x=lu.x;ld.y=rd.y;
ru.x=rd.x;ru.y=lu.y;
}
bool check(pt x)
{
int d1,d2,d3,d4;
d1=sig(cross(x,lu,ru));
d2=sig(cross(x,ld,rd));
d3=sig(cross(x,lu,ld));
d4=sig(cross(x,ru,rd));
if(d1*d2<0&&d3*d4<0) return 1;
return 0;
}
bool under(pt a,pt b,pt c)
{
return (min(b.x,c.x)<=a.x&&a.x<=max(b.x,c.x)&&
min(b.y,c.y)<=a.y&&a.y<=max(b.y,c.y));
}
bool test(pt a,pt b)
{
int d1,d2,d3,d4;
d1=sig(cross(s,a,b));
d2=sig(cross(e,a,b));
d3=sig(cross(a,s,e));
d4=sig(cross(b,s,e));
if(d1*d2<0&&d3*d4<0) return 1;
if(!d1&&under(s,a,b)) return 1;
if(!d2&&under(e,a,b)) return 1;
if(!d3&&under(a,s,e)) return 1;
if(!d4&&under(b,s,e)) return 1;
return 0;
}
bool check2()
{
int d1,d2,d3,d4;
d1=test(lu,ru);
d2=test(ru,rd);
d3=test(rd,ld);
d4=test(ld,lu);
if(d1||d2||d3||d4) return 1;
return 0;
}
void ac()
{
if(check(s)&&check(e)) printf("T\n");
else if(check2()) printf("T\n");
else printf("F\n");
}
int main()
{
// freopen("data.out","w",stdout);
int T;
scanf("%d",&T);
for(int i=1;i<=T;++i)
{
in();ac();
}
return 0;
}