POJ - 3304 :Segments__判断直线和线段是否 相交

本文介绍了一种算法,用于判断二维空间中是否存在一条直线能够与给定的所有线段相交。通过枚举线段端点并检查每一对端点确定的直线是否与所有线段有交点来实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 integern ≤ 100 showing the number of segments. After that, n lines containing four real numbersx1 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 numbersa 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!

Hint

Source


//题意:给出一些线段,问是否存在某条直线与所有线段都相交。
//分析:假设存在一条直线与所有线段都相交 ,那么这条直线可以通过旋转或者平移必定可以达到一个临界状态即恰好交与某两条线段的端点。所以只要枚举每两条线段的端点假定确定的一条直线(4种情况),判断这样假定的直线是否与所有线段相交即可!
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<cmath>
#include<cstdlib>
#include<queue>
#include<stack>
#include<map>
#include<vector>
#include<algorithm>
using namespace std;
#define maxn 105 
#define eps 1e-8

struct point 
{
	double x,y;
};
struct line
{
	point sp,ep;
}L[maxn];
int n;

double Len_ab(point a,point b)
{
	return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));
}

double x_multi(point p1,point p2,point p3)
{
	return (p2.x-p1.x)*(p3.y-p1.y)-(p3.x-p1.x)*(p2.y-p1.y);
}

bool Cross(point p1,point p2,point p3,point p4) //判断直线(p1,p2)和线段(p3,p4)是否相交
{
	double a=x_multi(p1,p2,p3);
	double b=x_multi(p1,p2,p4);
	if(fabs(a)<=eps) return true;
	if(fabs(b)<=eps) return true;
	if(a*b<=eps) return true;
	return false;
}

bool OK(point a,point b)
{
	if(Len_ab(a,b)<eps) //去重点
		return false;
	int i;
	for(i=0;i<n;i++)
		if(!Cross(a,b,L[i].sp,L[i].ep))
			return false;
	return true;
}

int main()
{
	int t,i,j;
	scanf("%d",&t);
	while(t--)
	{
		scanf("%d",&n);
		for(i=0;i<n;i++)
			scanf("%lf%lf%lf%lf",&L[i].sp.x,&L[i].sp.y,&L[i].ep.x,&L[i].ep.y);
		if(n==1)
		{
			puts("Yes!");
			continue;
		}
		for(i=0;i<n;i++)
			for(j=i+1;j<n;j++)
			{
				if(OK(L[i].sp,L[j].sp)||OK(L[i].sp,L[j].ep)||OK(L[i].ep,L[j].sp)||OK(L[i].ep,L[j].ep))
				{
					puts("Yes!");
					goto end;
				}
			}
		puts("No!");
		end:;
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值