模板--判断两条线段是否相交

摘自  https://www.cnblogs.com/Duahanlang/archive/2013/05/11/3073434.html

 

#include<cstdio>
#include<iostream>
#include<cstring>
using namespace std;
#define cs const
#define cp const P&
#define op operator
const  double eps = 1e-8;
inline int sig(double x) {return (x>eps)-(x<-eps);}

struct P{
    double x, y;
    void in() { scanf("%lf%lf", &x, &y); }
    P(double x=0.0, double y=0.0) : x(x), y(y) {}

    P op-(cp a)cs { return P(x-a.x, y-a.y); }
    double op^(cp a)cs { return x*a.y - y*a.x; }    //叉积
    double op*(cp a)cs {return x*a.x + y*a.y;}

    double cross(P a, P b) { return (a-*this) ^ (b-*this); }
    double dot(P a, P b)  { return (a-(*this)) * (b-(*this)); }
    bool on_seg(P a, P b) { return !sig(cross(a, b)) && sig(dot(a, b)) <= 0; }//判断是否在点上
};

bool seg(P a, P b, P c, P d) { //判断相交(a - b)线段 、(c - d)线段
    if(a.on_seg(c, d) || b.on_seg(c, d) || c.on_seg(a, b) || d.on_seg(a, b))
        return true;
    return sig(a.cross(b, c)*a.cross(b, d)) < 0 && sig(c.cross(d, a)*c.cross(d, b)) < 0;
}
int main()
{
    int t;
    P a,b,c,d;
    cin>>t;
    while(t--){
    cin>>a.x>>a.y>>b.x>>b.y>>c.x>>c.y>>d.x>>d.y;
    if(seg(a,b,c,d))
    puts("Yes");
    else
    puts("No");
    }
    return 0;
}

 

posted @ 2017-12-29 16:51  hinata_hajime  阅读(224)  评论(0编辑  收藏  举报