POJ 3304 直线和线段相交

Segments
Time Limit: 1000MS Memory Limit: 65536K
   

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 (x1y1) and (x2y2) 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条线段投影到这条直线上的公共点至少有一个。

题解:可以转化为找出一条直线,贯穿n条线段。那么我们假设能找到这样一条直线,那么它旋转时只要不到n条线段的端点,那么衍生出来的直线也是符合题意的,所以我们可以枚举任意两条线段的端点,找出满足题意的即可。
ps:判断一条直线与线段是否相交,就是分别对两个端点与直线的两个端点做叉积,如果乘积小于等于0,则没有交点。题目中还说两个点的距离小于1e-8就视为同一点,判断掉即可。

#include<iostream>
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<math.h>
using namespace std;
#define eps 1e-8
struct node{
	double x,y;
}p[205];
int n;
double multiply(node p0,node p1,node p2){//叉积
	return ((p1.x-p0.x)*(p2.y-p0.y)-(p2.x-p0.x)*(p1.y-p0.y));
}
int judge(node p1,node p2,int k){
	if (multiply(p[2*k-1],p1,p2)*multiply(p[2*k],p1,p2)<=1e-9)return 1;
	return 0;
}
int solve(){
	int i,j,k;
	for(i=1;i<=2*n;i++){
		for(j=i+1;j<=2*n;j++){//枚举两个端点
			if(fabs(p[i].x-p[j].x)<eps&&fabs(p[i].y-p[j].y)<eps)continue;
			for(k=1;k<=n;k++){//判断第k条线段是否穿过这条直线
				if(judge(p[i],p[j],k)==0)break;//如果没穿过,那就break掉
			}
			if(k>n)return 1;
		}
	}
	return 0;
}
int main(){
	int t;
	scanf("%d",&t);
	while(t--){
		int i,j;
		scanf("%d",&n);
		for(i=1;i<=n;i++){
			scanf("%lf%lf%lf%lf",&p[2*i-1].x,&p[2*i-1].y,&p[2*i].x,&p[2*i].y);
		}
		int ans=solve();
		if(ans)puts("Yes!");
		else puts("No!");
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值