POJ3304:Segments (几何:求一条直线与已知线段都有交点)

时间:2022-01-15 21:35:31

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 x1y1 x2 y2 follow, in which (x1y1) and (x2y2) 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条线段,问是否存在直线X,使得这些线段在直线上的投影有公共点。

思路:

转化一下,就是问是是否存在直线X,使得X的垂线L与每个线段都有公共点。如果存在L,那么把其中一些满足条件的L平移,

可以使得它结果两个已知线段的端点。

注意一下:

需要判断是否两点重合,开始我用的方法是fabs(x1-x2)<eps,fabs(y1-y2)<eps则重合,改为dist<=eps则重合就AC了。

#include<cmath>
#include<cstdio>
#include<cstdlib>
#include<iostream>
#include<algorithm>
using namespace std;
const int maxn=;
const double eps=1e-;
int N;
struct Cpoint
{
double x,y;
Cpoint(){}
Cpoint(double xx,double yy):x(xx),y(yy){}
};
struct Cline
{
Cpoint a,b;
Cline(){}
Cline(Cpoint aa,Cpoint bb):a(aa),b(bb){}
};
struct Vector
{
double x,y;
Vector(){}
Vector(double xx,double yy):x(xx),y(yy){}
double friend operator ^(Vector a,Vector b){
return a.x*b.y-b.x*a.y;
}
};
double dist(Cpoint a,Cpoint b)
{
return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));
}
Cline L[maxn];
bool check(Cpoint w, Cpoint v)
{
if(dist(w,v)<=eps) return false;// 判断两点重合,开始用点直接比较WA了。
Vector base(w.x-v.x,w.y-v.y);
for(int i=;i<=N;i++){
Vector e(L[i].a.x-v.x,L[i].a.y-v.y);
Vector p(L[i].b.x-v.x,L[i].b.y-v.y);
if((base^e)*(base^p)>eps) return false;
} return true;
}
bool find()
{
for(int i=;i<=N;i++)
for(int j=;j<=N;j++){
if(check(L[i].a,L[j].a)) return true;
if(check(L[i].a,L[j].b)) return true;
if(check(L[i].b,L[j].a)) return true;
if(check(L[i].b,L[j].b)) return true;
}
return false;
}
int main()
{
int T; double x,y,xx,yy;
scanf("%d",&T);
while(T--){
scanf("%d",&N);
for(int i=;i<=N;i++){
scanf("%lf%lf%lf%lf",&x,&y,&xx,&yy);
L[i]=Cline(Cpoint(x,y),Cpoint(xx,yy));
}
if(find()) printf("Yes!\n");
else printf("No!\n");
}
return ;
}