Segments POJ - 3304(计算几何基础判断两直线相交)

Segments POJ - 3304

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!

题意:

给出n条线段两个端点的坐标,问所有线段投影到一条直线上,如果这些所有投影至少相交于一点就输出Yes!,否则输出No!。

思路:

如果有存在这样的直线,过投影相交区域作直线的垂线,该垂线必定与每条线段相交,问题转化为问

是否存在一条线和所有线段相交

直线肯定经过两个端点。

枚举两个端点,然后确定一条直线,然后在枚举每条线看能否和其他线段相交

判断直线相交使用叉积:

Segments POJ - 3304(计算几何基础判断两直线相交)_第1张图片

如果两个直线相交如图直线 p1p2 p 1 p 2 AB A B 相交,那么点AB必然在点 p1 p 1 的两侧,所以算出叉积
p1p2×p1A p 1 p 2 × p 1 A p1p2×p1B p 1 p 2 × p 1 B 两个叉积得到的结果相乘符号必须为负才说明是相交的

code:

#include 
#include 
#include 
#include 
using namespace std;
const double eps = 1e-8;
struct Point{
    double x,y;
    Point(){}
    Point(double xx,double yy):x(xx),y(yy){}
}p[300];
struct Seg{
    Point p1,p2;
}s[110];
Point operator - (Point p,Point q){
    return Point(p.x - q.x,p.y - q.y);
}
int n;
double dis(Point p1,Point p2){
    return sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y));
}
double Cross(Point p1,Point p2){
    return p1.x * p2.y - p2.x * p1.y;
}
bool judge(Point p1,Point p2){
    if(dis(p1,p2) < eps) return false;
    for(int i = 0; i < n; i++){//判断两条直线叉积相乘大于0说明不相交
        if(Cross(p2 - p1,s[i].p1 - p1) * Cross(p2 - p1,s[i].p2 - p1) > eps)
            return false;
    }
    return true;
}
int main(){
    int T;
    scanf("%d",&T);
    while(T--){
        scanf("%d",&n);
        for(int i = 0; i < n; i++){
            scanf("%lf%lf%lf%lf",&s[i].p1.x,&s[i].p1.y,&s[i].p2.x,&s[i].p2.y);
        }
        int flag = 0;
        if(n == 1) flag = 1;
        else{
            for(int i = 0; i < n-1 && !flag; i++){
                for(int j = i+1; j < n && !flag; j++){//枚举两个端点
                    if(judge(s[i].p1,s[j].p1) || judge(s[i].p1,s[j].p2) || judge(s[i].p2,s[j].p1) || judge(s[i].p2,s[j].p2))
                        flag = 1;
                }   
            }
        }
        if(flag) printf("Yes!\n");
        else printf("No!\n");
    }
    return 0;
}

你可能感兴趣的:(计算几何)