题目来源:[NWPU][2014][TRN][19]二维计算几何基础
http://vjudge.net/vjudge/contest/view.action?cid=54080#problem/C
作者:npufz
题目:
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 x1y1x2y2 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 <cmath>
#include <cstring>
using namespace std;
bool intersection(const double &x1,const double &y1,const double &x2,const double &y2,
const double &x3,const double &y3,const double &x4,const double &y4 )
{
bool flag=false;double m1,m2;
flag=false;
m1=(x3-x1)*(y2-y1)-(y3-y1)*(x2-x1);
m2=(x4-x1)*(y2-y1)-(y4-y1)*(x2-x1);
if((m1*m2)<1.0e-8)
flag=true;
return flag;
}
int main()
{
int i,j,k,t,n;
double a[210][2];
bool flag;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
n*=2;
for(i=0;i<n;i++)
scanf("%lf%lf",&a[i][0],&a[i][1]);
flag=false;
for(i=0;i<n-1&&flag==false;i++)
for(j=i+1;j<n&&flag==false;j++)
{
if(fabs(a[i][0]-a[j][0])<1e-8&&fabs(a[i][1]-a[j][1])<1e-8) break;
for(k=0;k<n;k+=2)
{
if(intersection(a[i][0],a[i][1],a[j][0],a[j][1],a[k][0],a[k][1],a[k+1][0],a[k+1][1])==false)
break;
}
if(k==n) {flag=true;break;}
}
if(flag) printf("Yes!\n");
else printf("No!\n");
}
return 0;
}
反思:
这个题目其实等价于找到一条直线和所有的线段均有点,注意到如果这条直线存在,如果这条直线不经过所有线段中的两个,那么一定存在另一条经过两个端点的直线满足条件,这样就解决了问题,一开始通过所有的端点枚举直线时,没有考虑到枚举的两个端点可能是同一个点,就WA了,改正后就A了