poj3304-Segments-判断直线和线段是否相交

来源:互联网 发布:windows udp端口测试 编辑:程序博客网 时间:2024/05/25 23:57
Segments

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 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

321.0 2.0 3.0 4.04.0 5.0 6.0 7.030.0 0.0 0.0 1.00.0 1.0 0.0 2.01.0 1.0 2.0 1.030.0 0.0 0.0 1.00.0 2.0 0.0 3.01.0 1.0 2.0 1.0

Sample Output

Yes!Yes!No!

题意:是否存在一条直线,使得所有线段在其上的投影交于同一点
相当于求是否存在一条直线l交于所有线段,作直线l的垂线m,则m即为所求的直线
将所有线段的两个端点列出来,连接任意两个端点,形成一条直线,然后判断此直线和所有线段是否相交

#include<stdio.h>#include<math.h>const double eps=1e-8;struct point{    double x,y;}Seg[1000];int equ(point a,point b){    double dis;    dis=(a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y);    if(sqrt(dis) < eps) return 0;    else return 1;}double fun(point a,point b,point c){    return (c.x-a.x)*(b.y-a.y)-(c.y-a.y)*(b.x-a.x);}int judge(int n){    for(int i=0; i < n ; i++)    {        for(int j=i+1 ; j < n ; j++)        {            if(equ(Seg[i],Seg[j])==0) continue;            for(int k=0; k < n ; k+=2)            {                double d1,d2;                d1=fun(Seg[i],Seg[j],Seg[k]);                d2=fun(Seg[i],Seg[j],Seg[k+1]);                if(d1*d2>0)                    break;                if(k==n-2)                    return 1;            }        }    }    return 0;}int main(){    int T,n;    double x1,y1,x2,y2;    scanf("%d",&T);    while(T--)    {        scanf("%d",&n);        int j=0;        for(int i=0 ; i < n ; i++)        {            scanf("%lf%lf%lf%lf",&x1,&y1,&x2,&y2);            Seg[j].x=x1; Seg[j].y=y1;            Seg[j+1].x=x2; Seg[j+1].y=y2;            j+=2;        }        if(judge(2*n)) printf("Yes!\n");        else printf("No!\n");    }    return 0;}

0 0