「POJ3304」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 (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
1 2 3 4 5 6 7 8 9 10 11 12 |
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
1 2 3 |
Yes! Yes! No! |
题解
若存在这样一条直线,过投影相交区域作直线的垂线,该垂线必定与每条线段相交,问题转化为问是否存在一条
线和所有线段相交;
若存在一条直线与所有线段相机相交,将该线旋转,平移,直到不能再动为止,此时该直线必定经过这些线段的某两个端点;
所以枚举任意两个端点即可。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
#include<iostream> #include<cstdio> #include<cmath> #include<cstring> #define eps 1e-8 using namespace std; int T,n;bool flag; struct point{double x,y;}; struct seg{point a,b;}s[101]; point sub(point a,point b) {point t;t.x=a.x-b.x;t.y=a.y-b.y;return t;} double cross(point a,point b) {return a.x*b.y-b.x*a.y;} double turn(point p1,point p2,point p3) {return cross(sub(p2,p1),sub(p3,p1));} bool equ(double x,double y) {if(fabs(x-y)<eps)return 1;return 0;} bool jud(point a,point b) { if(equ(a.x,b.x)&&equ(a.y,b.y))return 0; for(int i=1;i<=n;i++) if(turn(a,b,s[i].a)*turn(a,b,s[i].b)>eps)return 0; return 1; } int main() { scanf("%d",&T); while(T--) { scanf("%d",&n); for(int i=1;i<=n;i++) scanf("%lf%lf%lf%lf",&s[i].a.x,&s[i].a.y,&s[i].b.x,&s[i].b.y); flag=0; for(int i=1;i<=n;i++) if(!flag)for(int j=1;j<=n;j++) { if(jud(s[i].a,s[j].a)){flag=1;break;} if(jud(s[i].a,s[j].b)){flag=1;break;} if(jud(s[i].b,s[j].a)){flag=1;break;} if(jud(s[i].b,s[j].b)){flag=1;break;} } if(!flag)printf("No!\n"); else printf("Yes!\n"); } return 0; } |