题目描述
平面直角坐标系中有一条线段AB和一条线段CD,求线段CD和线段AB的相交判断。
输入描述
输出描述
输入输出样例
输入:
3
6 2 3 4
4 5 2 2
7 7 10 1
7 7 3 9
1 6 3 5
2 5 1 4
输出:
2
1
0
最终代码c/c++
#include<bits/stdc++.h>
using namespace std;
const double pi = acos(-1.0); //高精度圆周率
const double eps = 1e-8; //偏差值
//判断x是否等于0
int sgn(double x)
{
if(fabs(x) < eps) return 0;
else return x<0?-1:1;
}
struct Point
{
double x, y;
void input(){ scanf("%lf%lf", &x, &y); }
Point(){}
Point(double x,double y):x(x),y(y){}
Point operator + (Point B){return Point(x+B.x,y+B.y);}
Point operator - (Point B){return Point(x-B.x,y-B.y);}
};
typedef Point Vector; //定义向量
double Cross(Point A,Point B){return A.x*B.y - A.y*B.x;} //叉积
double Dot(Vector A,Vector B){return A.x*B.x + A.y*B.y;} //点积
struct Line{
Point p1,p2; //线上的两个点
Line(){}
Line(Point p1,Point p2):p1(p1),p2(p2){}
};
//点和线段:0 点不在线段v上;1 点在线段v上
bool Point_on_seg(Point p, Line v){
return sgn(Cross(p-v.p1, v.p2-v.p1)) == 0 && sgn(Dot(p - v.p1,p- v.p2)) <= 0;
}
//线段相交
bool Cross_segment(Point a,Point b,Point c,Point d){//Line1:ab, Line2:cd
double c1=Cross(b-a,c-a),c2=Cross(b-a,d-a);
double d1=Cross(d-c,a-c),d2=Cross(d-c,b-c);
return sgn(c1)*sgn(c2)<=0 && sgn(d1)*sgn(d2)<=0; //1相交;0不相交
}
int main(){
int t; cin >> t;
while(t--)
{
Point a, b, c,d;
a.input(); b.input(); c.input();d.input();
int pos=Cross_segment(a,b,c,d);
if(pos==0) cout<<"0"<<endl; //不相交
else{
Line v1,v2;
v1=Line(a,b),v2=Line(c,d);
if(Point_on_seg(c,v1) || Point_on_seg(d,v1) || Point_on_seg(a,v2) || Point_on_seg(b,v2))
cout<<"1"<<endl; //交点在端点上,不规范相交
else
cout<<"2"<<endl; //交点不在端点上,规范相交
}
}
return 0;
}