Segments
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!
【思路分析】
给你若干个线段,需要你去判断能否在坐标系内找到一条直线,使得所有线段在这条直线上的投影至少有一个公共点。该问题可以转化为:将其中一个线段两端延长成为直线,然后去一一判断该直线和所有的线段是否都有交点,若能找到这条直线,那么就满足题意。
直线是否与线段相交可以根据叉积的性质来判断。
代码如下:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
#define maxn 105
#define eps 1e-8
int n;
struct Point
{
double x,y;
Point()
{
}
Point(double a,double b)
{
x = a;
y = b;
}
}point[maxn];
struct Segment
{
Point p1,p2;
Segment()
{
}
Segment(Point a,Point b)
{
p1 = a;
p2 = b;
}
}segment[maxn];
double cross(Point p0,Point p1,Point p2)
{
return (p1.x - p0.x) * (p2.y - p0.y) - (p1.y - p0.y) * (p2.x - p0.x);
}
double distances(Point p1,Point p2)
{
return sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y));
}
bool isIntersection(Segment l)
{
for(int i = 0;i < n;i++)
{
if(cross(segment[i].p1,l.p1,l.p2) * cross(segment[i].p2,l.p1,l.p2) > 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",&segment[i].p1.x,&segment[i].p1.y,&segment[i].p2.x,&segment[i].p2.y);
point[i * 2] = segment[i].p1;
point[i * 2 + 1] = segment[i].p2;
}
if(n == 1)
{
printf("Yes!\n");
continue;
}
bool flag = false;
for(int i = 0;i < n * 2;i++)
{
for(int j = i + 1;j < n * 2;j++)
{
if(distances(point[i],point[j]) >= eps && isIntersection(Segment(point[i],point[j])))
{
flag = true;
}
}
}
if(flag)
printf("Yes!\n");
else
printf("No!\n");
}
return 0;
}