原题目:
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!
中文概要:
3( t 组数)
2 (n 接下来有n条线段)
1.0 2.0 3.0 4.0 (分别是x1,y1,x2,y2)
4.0 5.0 6.0 7.0
问 是否存在一条直线,使得该直线和所有以上线段都相交。
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<cmath>
using namespace std;
#define MAX 150
#define MIN 1e-8
int n;
struct Point{
double x,y;
} Left[MAX],Right[MAX];
double det(Point p1,Point p2,Point p3){
return (p1.x-p3.x)*(p2.y-p3.y)-(p2.x-p3.x)*(p1.y-p3.y);//判断点p3是否在线段p1p2的左右
// x1y2+x3y1+x2y3-x3y2-x2y1-x1y3 不要这样直接乘..可能会爆掉
}
int judge(Point p1,Point p2){
if(abs(p1.x-p2.x)<MIN&&abs(p1.y-p2.y)<MIN)
return 0;
for(int i=0;i<n;i++)
if(det(p1,p2,Left[i])*det(p1,p2,Right[i])>MIN)
return 0;
return 1;
}
int main()
{
int T,result;
scanf("%d",&T);
while(T--)
{
scanf("%d",&n);
for(int i=0;i<n;i++)
{
scanf("%lf%lf%lf%lf",&Left[i].x,&Left[i].y,&Right[i].x,&Right[i].y);
}
result=0;
if(n<3)
result=true;
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
if(result)break;
if(judge(Left[i],Left[j])) result=1;
else if(judge(Left[i],Right[j])) result=1;
else if(judge(Right[i],Left[i])) result=1;
else if(judge(Right[i],Right[j])) result=1;
}
if(result)break;
}
if(result)
printf("Yes!\n");
else
printf("No!\n");
}
return 0;
}
思路:
每两条线段的各一个端点,比如线段AB 和线段CD 选取AC AD BC BD依次连成直线,再依次判断剩下的线段是否都和这条直线有交点。 用到了叉积来判断P3与P1P1的关系
枚举所有可能的两点之间情况,重点在(p1.x-p3.x)*(p2.y-p3.y)-(p2.x-p3.x)*(p1.y-p3.y);//判断点p3是否在线段p1p2的左右
只要四种极端情况满足( 除这两个点构成的线段以外的所有线段都和该直线相交 )这个条件,就可以输出yes了,否则输出no。
线段是否相交模板:
int judge(Point p1,Point p2)
{
if(abs(p1.x-p2.x) < MIN && abs(p1.y-p2.y) < MIN)
return 0;
for(int i=0; i<n; i++)
if(det(p1, p2, Left[i])*det(p1, p2, Right[i]) > MIN) return 0;//每个点都进行判断
return 1;
}