两条线段可以看作是两个向量;
一条线段跨立另一条线段的条件是:一条线段的端点分别到另一条线段两个端点构成的向量在该线段两侧;(可能不相交)
而两条线段互相跨立,即相交,就可判断。
模板分享
#include <iostream>
#include <stdio.h>
#include <math.h>
#include <algorithm>
#define equals(a,b) (fabs((a)-(b))<EPS)
#define EPS 1e-10
using namespace std;
struct Point{
double x,y;
Point(){}
Point(double x,double y){
this->x=x;
this->y=y;
}
};
struct line{
Point p1,p2;
};
Point operator +(Point a,Point b){
return Point(a.x+b.x,a.y+b.y);
}
Point operator -(Point a,Point b){
return Point(a.x-b.x,a.y-b.y);
}
Point operator *(Point a,double t){
return Point(a.x*t,a.y*t);
}
//向量的模
double morn (Point a){
return sqrt(a.x*a.x+a.y*a.y);
}
//向量点积
double dot(Point a,Point b){
return (a.x*b.x+a.y*b.y);
}
//向量叉积
double cross(Point a,Point b){
return (a.x*b.y-a.y*b.x);
}
//两向量平行
bool parallel(Point a,Point b){
return equals(cross(a,b),0.0);
}
//向量与点的位置
int where(Point p0,Point p1,Point p2){
Point a=p1-p0;
Point b=p2-p0;
if(cross(a,b)>EPS)return 1;
if(cross(a,b)<-EPS)return -1;
if(dot(a,b)<-EPS)return 2;
if(morn(a)<morn(b))return -2;
return 0;
}
//线段相交
bool interest(Point p1,Point p2,Point q1,Point q2){
bool ans=(where(p1,p2,q1)*where(p1,p2,q2)<=0&&where(q1,q2,p1)*where(q1,q2,p2)<=0);
return ans;
}
//线段交点
Point getpoint(line l1,line l2){
l1.p2=l1.p1-l1.p2,l2.p2=l2.p1-l2.p2;
double A1 = l1.p2.y,B1 = l1.p2.x;
double C1 = l1.p2.y*l1.p1.x-l1.p2.x*l1.p1.y;
double A2 = l2.p2.y,B2 = l2.p2.x;
double C2 = l2.p2.y*l2.p1.x-l2.p2.x*l2.p1.y;
double x = (C1*B2-C2*B1)/(A1*B2-A2*B1);
double y = (C1*A2-C2*A1)/(A1*B2-A2*B1);
return Point(x, y);
}