判断直线与线段是否相交
判断直线与线段是否相交,这个刘汝佳的板子上没有,但是稍微分析一下就可以得到了,这个是线段相交的简化版。
// 显然只需要b1,b2在a1,a2两侧即可,不需要判断a1,a2是否在b1,b2两侧
// 其中a1,a2是直线,b1,b2是线段
bool SegLineInt(Point a1,Point a2,Point b1,Point b2) {
double c1 = Cross(a2-a1,b1-a1), c2 = Cross(a2-a1,b2-a1);
return dcmp(c1)*dcmp(c2)<=0;
}
Segments
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 19074 Accepted: 6019
Description
Given n segments in the two dimensional space, write a program, which determines if there exists a line such that after projecting these segments on it, all projected segments have at least one point in common.
Input
Input begins with a number T showing the number of test cases and then, T test cases follow. Each test case begins with a line containing a positive integer n ≤ 100 showing the number of segments. After that, n lines containing four real numbers x1 y1 x2 y2 follow, in which (x1, y1) and (x2, y2) are the coordinates of the two endpoints for one of the segments.
Output
For each test case, your program must output “Yes!”, if a line with desired property exists and must output “No!” otherwise. You must assume that two floating point numbers a and b are equal if |a - b| < 10-8.
Sample Input
3
2
1.0 2.0 3.0 4.0
4.0 5.0 6.0 7.0
3
0.0 0.0 0.0 1.0
0.0 1.0 0.0 2.0
1.0 1.0 2.0 1.0
3
0.0 0.0 0.0 1.0
0.0 2.0 0.0 3.0
1.0 1.0 2.0 1.0
Sample Output
Yes!
Yes!
No!
Source
分析
判断是否存在一条直线,让所有线段在直线上的投影存在一个公共点。这个问题可以转化为这样的问题:
是否存在一条直线可以穿过所有线段,进而转化成经过某两个线段端点的直线能否穿过所有线段。(具体证明可以自行百度)
现在问题简化了,只需要枚举两个端点(包括同一条线段的)判断是否相交就行了。
坑:枚举的两个端点可能重合
参考代码
#include <cstdio>
#include <iostream>
#include <cmath>
const double eps=1e-8;
using namespace std;
struct Point {
double x, y;
Point(double x=0, double y=0