51nod_1264_线段相交
判断两线段是否相交
题目描述
给出平面上两条线段的两个端点,判断这两条线段是否相交(有一个公共点或有部分重合认为相交)。 如果相交,输出"Yes",否则输出"No"。
Input
第1行:一个数T,表示输入的测试数量(1 <= T <= 1000)
第2 - T + 1行:每行8个数,x1,y1,x2,y2,x3,y3,x4,y4。(-10^8 <= xi, yi <= 10^8)
(直线1的两个端点为x1,y1 | x2, y2,直线2的两个端点为x3,y3 | x4, y4)
Output
输出共T行,如果相交输出"Yes",否则输出"No"。
Input示例
2
1 2 2 1 0 0 2 2
-1 1 1 1 0 0 1 -1
Output示例
Yes
No
解题思路
利用向量叉乘有方向的性质判断线段的两个端点和另一个线段的关系
AC代码
#include<iostream>
#include<algorithm>
using namespace std;
struct Point {//点
double x, y;
Point() {}
Point(int a, int b) {
x = a;
y = b;
}
};
struct Line {//线段
Point a, b;
Line() {}
Line(Point x, Point y) {
a = x;
b = y;
}
};
bool judge(Point &a, Point &b, Point &c, Point &d)
{
if (!(min(a.x, b.x) <= max(c.x, d.x) && min(c.y, d.y) <= max(a.y, b.y) && min(c.x, d.x) <= max(a.x, b.x) && min(a.y, b.y) <= max(c.y, d.y)))
return false;
double u, v, w, z;//分别记录两个向量
u = (c.x - a.x)*(b.y - a.y) - (b.x - a.x)*(c.y - a.y);
v = (d.x - a.x)*(b.y - a.y) - (b.x - a.x)*(d.y - a.y);
w = (a.x - c.x)*(d.y - c.y) - (d.x - c.x)*(a.y - c.y);
z = (b.x - c.x)*(d.y - c.y) - (d.x - c.x)*(b.y - c.y);
return (u*v <= 0.00000001 && w*z <= 0.00000001);
}
int main() {
int t;
cin >> t;
while (t--) {
Point p1, p2, p3, p4;
cin >> p1.x >> p1.y >> p2.x >> p2.y >> p3.x >> p3.y >> p4.x >> p4.y;
if (judge(p1, p2, p3, p4)) {
cout << "Yes\n";
}
else
cout << "No\n";
}
return 0;
}