您的位置:首页 > 其它

[CG]Intersection of Line Segments(0163)(计算几何,求线段是否相交)

2017-08-16 19:25 302 查看
Giving 2 line segments on a plane, decide whether they intersect or not. Pay attention, endpoint contacts should be considered intersection.

Description

The input starts with a line containing a single integer T, the number of test cases. Each test case consists of 2 lines, with each describing a line segment. For each line, there're 4 integers within [-100, 100]. The first two denote one endpoint and the last
two denote the other. Points are represented by x and y coordinates.

Input

If the 2 line segments given intersect, display "True", otherwise display "False".

Output

1
2
3

1
0 0 1 0
1 0 1 1

Sample Input

1

True

Sample Output

"Cross Product" is essential in "Computational Geometry". One of the many uses of cross product is to decide the relative position of geometric objects, such as points and line segments. This problem can also be solved efficiently and easily using cross product
with no precision loss(no division operation is used).

/*
*
题意:
给你两个点,代表一条线段,再给你另外两个点代表另外一条线段
问你这两条线段是否相交

题解:
用矢量叉积求解。什么?
你不知道什么是矢量叉积,去看我的上一篇博客吧。
*/

#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<math.h>
using namespace std;

struct node
{
int x, y;
};

int dig(node x0, node x1, node x2)
{
return (x2.x - x0.x)*(x1.y - x0.y) - (x1.x - x0.x)*(x2.y - x0.y);
}

int main()
{
int t;
node a1, a2, b1, b2;
cin >> t;
while (t--)
{
cin >> a1.x >> a1.y >> a2.x >> a2.y;
cin >> b1.x >> b1.y >> b2.x >> b2.y;
if ((b1.x >= min(a1.x, a2.x) && b1.x <= max(a1.x, a2.x) && b1.y >= min(a1.y, a2.y) && b1.y <= max(a1.y, a2.y))
|| (b2.x >= min(a1.x, a2.x) && b2.x <= max(a1.x, a2.x) && b2.y >= min(a1.y, a2.y) && b2.y <= max(a1.y, a2.y)))
{
if (dig(a1, a2, b1)*dig(a1, a2, b2) <= 0)
{
cout << "True" << endl;
}
else
{
cout << "False" << endl;
}
}
else
{
cout << "False" << endl;
}

}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: