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!
解题思路:
画图容易想到,原题 ⇔ 是否存在一直线与这些线段都相交
考虑极限情况,枚举每个线段两端点最多组成 (n * n * 2 )条直线
代码:
#include<iostream>
#include<string.h>
#include<stdio.h>
#include<math.h>
using namespace std;
inline int read(){
int x=0,f=0;char ch=getchar();
while(ch>'9'||ch<'0')f|=ch=='-',ch=getchar();
while(ch>='0'&&ch<='9')x=(x<<3)+(x<<1)+(ch^48),ch=getchar();
return f?-x:x;
}
const int maxn=1e2+3;
const double eps=1e-8;
struct POINT{
double x,y;
POINT(double x=0,double y=0):x(x),y(y){}
};
struct LINESEG{
POINT s,e;
LINESEG(POINT s=0,POINT e=0):s(s),e(e){}
}lineseg[maxn],line[maxn*maxn*2];
double multiply(POINT sp,POINT ep,POINT op){
return((sp.x-op.x)*(ep.y-op.y)-(ep.x-op.x)*(sp.y-op.y));
}
bool intersect_l(LINESEG u,LINESEG v){//线段v所在直线与线段u相交时返回true
return multiply(u.s,v.e,v.s)*multiply(v.e,u.e,v.s)>=0;
}
bool equal_point(POINT p1,POINT p2){
return ((fabs(p1.x-p2.x)<eps)&&(fabs(p1.y-p2.y)<eps));
}
int main(){
int t=read();
double x1,y1,x2,y2;
while(t--){
int n=read(),cnt=0,op=1;
for(int i=0;i<n;++i){
scanf("%lf%lf%lf%lf",&x1,&y1,&x2,&y2);
lineseg[i]=LINESEG(POINT(x1,y1),POINT(x2,y2));
}
if(n==1||n==2){
puts("Yes!");
continue;
}
for(int i=0;i<n;++i)
for(int j=i+1;j<n;++j){
if(!equal_point(lineseg[i].s,lineseg[j].s))line[cnt++]=LINESEG(lineseg[i].s,lineseg[j].s);
if(!equal_point(lineseg[i].s,lineseg[j].e))line[cnt++]=LINESEG(lineseg[i].s,lineseg[j].e);
if(!equal_point(lineseg[i].e,lineseg[j].s))line[cnt++]=LINESEG(lineseg[i].e,lineseg[j].s);
if(!equal_point(lineseg[i].e,lineseg[j].e))line[cnt++]=LINESEG(lineseg[i].e,lineseg[j].e);
}
for(int i=0;i<cnt;++i){
int ok=1;
for(int j=0;j<n;++j)if(!intersect_l(lineseg[j],line[i])){
ok=0;
break;
}
if(ok){
puts("Yes!");
op=0;
break;
}
}
if(op)puts("No!");
}
return 0;
}