POJ 1410 Intersection <计算几何(线段相交判断)>

来源:互联网 发布:linux jar 解压命令 编辑:程序博客网 时间:2024/04/30 11:58

题目

分析:求给定的线段是否与给定的矩形相交。仔细审题啊,好多人吃了英语不好的亏。。另外就是线段之间非规范相交的判断方法,与直线与线段是不同的。

代码:

#include <iostream>#include <cstdio>#include <algorithm>#include <cmath>using namespace std;struct Point;typedef Point Vec;const double EPS=1e-8;int dblcmp(double x){    return fabs(x)<EPS?0:(x>0?1:-1);}struct Point{    double x,y;    Point(){}    Point(double xx,double yy):x(xx),y(yy){}    Vec operator -(Point p){        return Vec(x-p.x,y-p.y);    }    double operator ^(Vec v){        return x*v.y-y*v.x;    }};struct Segment{    Point p1,p2;    Segment(){}    Segment(Point pp1,Point pp2):p1(pp1),p2(pp2){}    bool isCross(Segment s){        return max(p1.x,p2.x)>=min(s.p1.x,s.p2.x)&&                max(s.p1.x,s.p2.x)>=min(p1.x,p2.x)&&                max(p1.y,p2.y)>=min(s.p1.y,s.p2.y)&&                max(s.p1.y,s.p2.y)>=min(p1.y,p2.y)&&                dblcmp((p2-p1)^(s.p1-p1))*dblcmp((p2-p1)^(s.p2-p1))<=0&&                dblcmp((s.p2-s.p1)^(p1-s.p1))*dblcmp((s.p2-s.p1)^(p2-s.p1))<=0;    }};struct Rectangle{    Segment s[4];    double area;    Rectangle(){}    Rectangle(double _xLeft,double _yTop,double _xRight,double _yBottom){        double xLeft=min(_xLeft,_xRight);        double xRight=max(_xLeft,_xRight);        double yBottom=min(_yBottom,_yTop);        double yTop=max(_yBottom,_yTop);        s[0]=Segment(Point(xLeft,yBottom),Point(xRight,yBottom));        s[1]=Segment(Point(xRight,yBottom),Point(xRight,yTop));        s[2]=Segment(Point(xRight,yTop),Point(xLeft,yTop));        s[3]=Segment(Point(xLeft,yTop),Point(xLeft,yBottom));        area=(xRight-xLeft)*(yTop-yBottom);    }    bool inRectangle(Point p){        double areaTemp=0.0;        for(int i=0;i<4;++i){            areaTemp+=fabs((s[i].p1-p)^(s[i].p2-p));        }        return fabs(areaTemp/2.0-area)<EPS;    }    bool intersection(Segment seg){        for(int i=0;i<4;++i){            if(seg.isCross(s[i])) return true;        }        return inRectangle(seg.p1);    }};int main(){    ios::sync_with_stdio(false);    int n;    cin>>n;    double x1,y1,x2,y2,xl,xr,yt,yb;    while(n--){        cin>>x1>>y1>>x2>>y2>>xl>>yt>>xr>>yb;        if(Rectangle(xl,yt,xr,yb).intersection(Segment(Point(x1,y1),Point(x2,y2))))            cout<<'T'<<endl;        else cout<<'F'<<endl;    }    return 0;}
阅读全文
0 0