http://poj.org/problem?id=1410
给定一个矩形和一条线段,求线段能否交矩形,线段与矩形的边或矩形内部有交点即为交。
很简单的一道判断线段相交的题目,不过要正确理解题目意思:相交要包括矩形的内部,即线段在矩形内部也是True。(The rectangle consists of four straight lines and the area in between.)题目说的左上、右下并非座标中的位置,数据给的点也会是左下、右上!!!(The terms top left and bottom right do not imply any ordering of coordinates. )
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<algorithm>
using namespace std;
struct point
{
double x,y;
}p[10];
double multi(point p0,point p1,point p2)
{
return (p1.x-p0.x)*(p2.y-p0.y)-(p2.x-p0.x)*(p1.y-p0.y);
}
bool is(point s1,point e1,point s2,point e2)
{
return (max(s1.x,e1.x)>=min(s2.x,e2.x))&&
(max(s2.x,e2.x)>=min(s1.x,e1.x))&&
(max(s1.y,e1.y)>=min(s2.y,e2.y))&&
(max(s2.y,e2.y)>=min(s1.y,e1.y))&&
(multi(s1,s2,e1)*multi(s1,e1,e2)>=0)&&
(multi(s2,s1,e2)*multi(s2,e2,e1)>=0);
}
int main()
{
int cas,i,flag;
double maxx,maxy,minx,miny;
scanf("%d",&cas);
while(cas--)
{
for(i=0;i<4;i++)
scanf("%lf%lf",&p[i].x,&p[i].y);
p[4].x=p[3].x;
p[4].y=p[2].y;
p[5].x=p[2].x;
p[5].y=p[3].y;
flag=1;
if(is(p[0],p[1],p[2],p[5])||is(p[0],p[1],p[5],p[3])||is(p[0],p[1],p[3],p[4])||is(p[0],p[1],p[4],p[2]))
flag=0;
maxx=max(p[2].x,p[3].x);
maxy=max(p[2].y,p[3].y);
minx=min(p[2].x,p[3].x);
miny=min(p[2].y,p[3].y);
if(p[0].x>=minx&&p[0].x<=maxx&&p[0].y>=miny&&p[0].y<=maxy)
flag=0;
if(flag)
cout<<"F"<<endl;
else
cout<<"T"<<endl;
}
return 0;
}
测试数据:
68
4 9 11 2 1 1 7 5
11 2 4 9 1 1 7 5
12 12 24 24 19 5 25 17
4 6 15 9 1 1 11 11
19 5 25 17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