线段相交问题

思路:

1.判断俩线段是否相交,首先可以使用线段正交的代码

bool SegmentProperIntersection(Point a1,Point a2,Point b1,Point b2)
{
    double c1=Cross(a2-a1,b1-a1),c2=Cross(a2-a1,b2-a1);
    double c3=Cross(b2-b1,a1-b1),c4=Cross(b2-b1,a2-b1);

    return dcmp(c1)*dcmp(c2)<0 && dcmp(c3)*dcmp(c4)<0;
}

完整代码如下:

#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstdio>

using namespace std;
const double eps=1e-10;

struct Point{
    double x,y;

    Point(double x=0,double y=0):x(x),y(y)
    {

    }
};

typedef Point Vector;

Vector operator +(Vector A,Vector B)
{
    return Vector(A.x+B.x,A.y+B.y);
}

Vector operator -(Vector A,Vector B)
{
    return Vector(A.x-B.x,A.y-B.y);
}

double Dot(Vector A,Vector B)
{
    return A.x*B.x+A.y*B.y;
}

int dcmp(double x)
{
    if(fabs(x)<eps) return 0;
    else 
        return x<0?-1:1;
}

double Length(Vector A)
{
    return sqrt(Dot(A,A));
}

double Cross(Vector A,Vector B)
{
    return A.x*B.y-A.y*B.x;
}

bool SegmentProperIntersection(Point a1,Point a2,Point b1,Point b2)
{
    double c1=Cross(a2-a1,b1-a1),c2=Cross(a2-a1,b2-a1);
    double c3=Cross(b2-b1,a1-b1),c4=Cross(b2-b1,a2-b1);

    return dcmp(c1)*dcmp(c2)<0 && dcmp(c3)*dcmp(c4)<0;
}

int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        Point p1,p2,p3,p4;
        scanf("%lf%lf%lf%lf",&p1.x,&p1.y,&p2.x,&p2.y);
        scanf("%lf%lf%lf%lf",&p3.x,&p3.y,&p4.x,&p4.y);
        if(SegmentProperIntersection(p1,p2,p3,p4))
        {
            puts("Yes");
        }
        else 
            puts("No");


    }


    return 0;
}
全部评论

相关推荐

05-26 10:24
门头沟学院 Java
qq乃乃好喝到咩噗茶:其实是对的,线上面试容易被人当野怪刷了
找工作时遇到的神仙HR
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务