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=1要特殊处理。
//判断线段和直线是否相交。
#include<cstdio>
#include<cstring>
using namespace std;
#define inf 1e-8
#define abs(x) ((x>0)?x:-(x))
struct point
{
double x,y;
point(){};
point(double a,double b){x=a;y=b;};
};
struct line
{
point s,e;
line(){};
line(point a,point b):s(a),e(b){};
}seg[105];
int n;
double cross(point a,point b,point o)
{
return (a.x-o.x)*(b.y-o.y)-(a.y-o.y)*(b.x-o.x);
}
bool check(point a,point b)
{
if(abs(a.x-b.x)<inf&&abs(a.y-b.y)<inf) return false;
for(int i=0;i<n;++i)
{
if(cross(a,b,seg[i].s)*cross(a,b,seg[i].e)>inf)
return false;
}
return true;
}
int main()
{
int t;
double x1,y1,x2,y2;
scanf("%d",&t);
for(bool flag=false;t--;flag=false)
{
scanf("%d",&n);
for(int i=0;i<n;++i)
{
scanf("%lf%lf%lf%lf",&x1,&y1,&x2,&y2);
seg[i]=line(point(x1,y1),point(x2,y2));
}
if(n==1) flag=true;
for(int i=0;i<n&&!flag;++i)
for(int j=i+1;j<n;++j)
{
if(check(seg[i].s,seg[j].s)||check(seg[i].s,seg[j].e)||check(seg[i].e,seg[j].s)||check(seg[i].e,seg[j].e))
{
flag=true;
break;
}
}
if(flag)
puts("Yes!");
else
puts("No!");
}
return 0;
}

本文探讨了如何确定是否存在一条直线,使得给定的二维空间中的多条线段在此直线上的投影至少有一个公共点。通过分析输入数据并利用几何运算,提供了一种有效的算法实现。
573

被折叠的 条评论
为什么被折叠?



