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

来源:互联网 发布:手机网站的空间域名 编辑:程序博客网 时间:2024/06/05 03:17

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;}




阅读全文
0 0