您的位置:首页 > 其它

poj 1410 判断线段与长方形是否相交

2011-10-20 14:30 344 查看
有点恶心,线段完全在长方形内,也算相交。。。。

还好热心网友发了数据 http://hi.baidu.com/lewutian/blog/item/9a8a38ece87cd52c62d09fb5.html

#include<stdio.h>
#include<math.h>
const double eps = 1e-8;
struct Point {
double x, y;
Point operator - (const Point& t) const {
Point tmp;
tmp.x = x - t.x;
tmp.y = y - t.y;
return tmp;
}
Point operator + (const Point& t) const {
Point tmp;
tmp.x = x + t.x;
tmp.y = y + t.y;
return tmp;
}
bool operator == (const Point& t) const {
return fabs(x-t.x) < eps && fabs(y-t.y) < eps;
}
}GP;
struct Line {
double a, b, c;
};
Line Turn(Point s, Point e) {										// 线段转直线表达式
Line ln;
ln.a = s.y - e.y;
ln.b = e.x - s.x;
ln.c = s.x*e.y - e.x*s.y;
return ln;
}
bool Line_Inst(Line l1, Line l2, Point &p) {						// 直线相交
double d = l1.a*l2.b - l2.a*l1.b;
if ( fabs(d) < eps )    return false;
p.x = (-l1.c*l2.b + l2.c*l1.b) / d;
p.y = (-l1.a*l2.c + l2.a*l1.c) / d;
return true;
}
bool dotOnSeg(Point p, Point s, Point e) {							// 点是否在线段上
if ( p == s || p == e )		// 看具体情况端点是否合法
return true;
return fabs((p-s).x*(p-e).y - (p-e).x*(p-s).y) < eps &&
(p.x-s.x)*(p.x-e.x)<eps && (p.y-s.y)*(p.y-e.y)<eps;
}
inline double min(double a,double b)
{
return a<b?a:b;
}
inline double max(double a,double b)
{
return a>b?a:b;
}
int main()
{
int t,i;
Point a,b,ta,tb;
Point p[5];
Point tp;
scanf("%d",&t);
while(t--)
{
scanf("%lf%lf%lf%lf%lf%lf%lf%lf",&a.x,&a.y,&b.x,&b.y,&ta.x,&ta.y,&tb.x,&tb.y);
double x1=min(ta.x,tb.x);
double x2=max(ta.x,tb.x);
double y1=min(ta.y,tb.y);
double y2=max(ta.y,tb.y);
p[0].x=x1,p[0].y=y1;
p[1].x=x2,p[1].y=y1;
p[2].x=x2,p[2].y=y2;
p[3].x=x1,p[3].y=y2;
Line l2=Turn(a,b);
if(a.x>=x1&&a.x<=x2&&a.y>=y1&&a.y<=y2) {printf("T\n");continue;}
int flag=0;
for(i=0;i<4;i++)
{
Line l1;
l1=Turn(p[i],p[(i+1)%4]);
if(Line_Inst(l1,l2,tp))
{
if(dotOnSeg(tp,a,b)&&dotOnSeg(tp,p[i],p[(i+1)%4]))
{
flag=1;
break;
}
}
}
if(flag) printf("T\n");
else printf("F\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: