POJ 3304 计算几何 题解

时间:2022-02-06 19:00:53

Segments
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 13837 Accepted: 4432

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!

Source

mirkabir University of Technology Local Contest 2006

【解题报告】
题目大意:在坐标中给你很n条线段(以首尾坐标的形式给出),(如果浮点数的差值在1e-8以内我们认为他是一样的)。询问是否存在一条直线,以上所有线段在这条直线上的投影至少有一处相互重合。
首先我们可以发现,如果n=1或n=2,肯定是存在的。
接着我们又可以发现,如果存在一条直线可以穿过所有的线段,说明题目中给出的条件是成立的。
然后判断就可以了。

代码如下:

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
#define eps 1e-8

int t,n;
struct Point
{
double x,y;
}s[105],e[105];

double mult(Point sp,Point ep,Point op)
{
return (sp.x-op.x)*(ep.y-op.y)-(ep.x-op.x)*(sp.y-op.y);
}
bool judge(Point p1,Point p2)
{
if(abs(p1.x-p2.x)<eps && abs(p1.y-p2.y)<eps)
return false;
for(int i=0;i<n;i++)
if(mult(p1,p2,s[i])*mult(p1,p2,e[i])>eps)
return false;
return true;
}
int main()
{
// freopen("POJ3340","r",stdin);
int t;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
for(int i=0;i<n;i++)
scanf("%lf%lf%lf%lf",&s[i].x,&s[i].y,&e[i].x,&e[i].y);
bool flag=false;
if(n<=2) flag=true;
for(int i=0;i<n&&!flag;i++)
for(int j=i+1; j<n && !flag ;j++)
{
if(judge(s[i],s[j])) flag=true;
else if(judge(s[i],e[j])) flag=true;
else if(judge(e[i],s[j])) flag=true;
else if(judge(e[i],e[j])) flag=true;
}
if(flag) printf("Yes!\n");
else printf("No!\n");
}
return 0;
}