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

题目

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

代码:

#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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值