首页 > 代码库 > poj3304计算几何直线与线段关系

poj3304计算几何直线与线段关系

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!
一开始看不懂题意只好搜题意,看懂了题意之后还是花了两个多小时wa了七遍,只好看题解,可能是精度的地方写搓了>.<坑爹啊
叉乘判断线段的两端点是不是在直线的两侧
#include<map>
#include<set>
#include<list>
#include<cmath>
#include<queue>
#include<stack>
#include<vector>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define pi acos(-1)
#define ll long long
#define mod 1000000007

using namespace std;

const double eps=1e-8;
const int N=1005,maxn=100005,inf=0x3f3f3f3f;

struct point{
    double x,y;
};
struct line{
   point a,b;
}l[N];

int n;
double mul(point p,point u,point v)
{
    return (u.x-v.x)*(p.y-u.y)-(u.y-v.y)*(p.x-u.x);
}
bool ok(point u,point v)
{
    if(fabs(u.x-v.x)<eps&&fabs(u.y-v.y)<eps)return 0;
    for(int i=0;i<n;i++)
        if(mul(l[i].a,u,v)*mul(l[i].b,u,v)>=eps)
           return 0;
    return 1;
}
int main()
{
    int t;
    cin>>t;
    while(t--){
        cin>>n;
        for(int i=0;i<n;i++)
            cin>>l[i].a.x>>l[i].a.y>>l[i].b.x>>l[i].b.y;
        if(n<=2)
        {
            cout<<"Yes!"<<endl;
            continue;
        }
        bool flag=0;
        for(int i=0;i<n&&!flag;i++)
        {
            if(ok(l[i].a,l[i].b))flag=1;
            for(int j=i+1;j<n&&!flag;j++)
                if(ok(l[i].a,l[j].a)||ok(l[i].a,l[j].b)||ok(l[i].b,l[j].a)||ok(l[i].b,l[j].b))
                   flag=1;
        }
        if(flag)cout<<"Yes!"<<endl;
        else cout<<"No!"<<endl;
    }
    return 0;
}

 

poj3304计算几何直线与线段关系