您的位置:首页 > 其它

POJ 3304 直线和线段相交

2016-08-15 19:51 344 查看
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.InputInput 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 containingfour real numbers x1 y1 x2 y2 follow, in which (x1, y1) and (x2, y2) are the coordinates of thetwo endpoints for one of the segments.OutputFor 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-8struct 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;}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: