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!
是否存在一条直线使得所有线段在其上的投影至少有一个公共点。
摘自其他博主的两幅图。
由图二可以看出 如果存在一条极端的直线即在任意两个端点上有一条直线与其他线段都相交则这条直线的垂线就是答案;
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
using namespace std;
int t,n;
const int d=1e-8;
typedef struct
{
double x1,y1,x2,y2;
} node;
node e[105];
int dis(double x,double y,double a,double b)
{
if(sqrt((x-a)*(x-a)+(y-b)*(y-b))<1e-8) //判断两点是否相等即是否同一点
return 1;
return 0;
}
double kk(double x,double y,double x1,double y1,double x2,double y2)
{
return (x1-x)*(y2-y)-(x2-x)*(y1-y); //向量叉积
}
int check(double x1,double y1,double x2,double y2)
{
if(dis(x1,y1,x2,y2))
return 0;
for(int i=1; i<=n; i++)
{
if(kk(e[i].x1,e[i].y1,x1,y1,x2,y2)*
kk(e[i].x2,e[i].y2,x1,y1,x2,y2)>d) //大于1e-8说明两点在线段的同一侧,不相交
return 0;
}
return 1;
}
int main()
{
cin>>t;
while(t--)
{
int flag=0;
cin>>n;
for(int i=1; i<=n; i++)
cin>>e[i].x1>>e[i].y1>>e[i].x2>>e[i].y2;
if(n==1)
{
puts("Yes!");
continue;
}
for(int i=1; i<=n; i++)
for(int j=i+1; j<=n; j++)
{
if(check(e[i].x1,e[i].y1,e[j].x1,e[j].y1)||
check(e[i].x1,e[i].y1,e[j].x2,e[j].y2)||
check(e[i].x2,e[i].y2,e[j].x1,e[j].y1)||
check(e[i].x2,e[i].y2,e[j].x2,e[j].y2))
{
flag=1;
break;
}
}
if(flag) puts("Yes!");
else puts("No!");
}
return 0;
}