C - Segments POJ - 3304 (判断线段相交)

题目链接:https://vjudge.net/contest/276358#problem/C

题目大意:给你n条线段,问你是否存在一条线段使得所有的线段在这条直线的投影至少具有一个交点?

具体思路:这个题转换一下思路,假设存在一条直线与所有的线段都相交,那么这条直线的垂线就是题目中所求的直线,我们可以把所有的端点都遍历一遍,询问一下看有没有符合条件的直线就可以了。

AC代码:

 1 /*************************************************************************
 2     > File Name: hqx.cpp
 3     > Author: ma6174
 4     > Mail: [email protected] 
 5     > Created Time: 2019年01月28日 星期一 00时24分52秒
 6  ************************************************************************/
 7 #include<iostream>
 8 #include<stack>
 9 #include<stdio.h>
10 #include<iomanip>
11 #include<cmath>
12 using namespace std;
13 # define ll long long 
14 const int maxn = 300+100;
15 const double eps = 1e-8;
16 struct node{
17 double x1,y1;
18 double x2,y2;
19 }q[maxn];
20 int n;
21 double dis(double x1,double y1,double x2,double y2){
22 return sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1));
23 }
24 double cal(double x1,double y1,double x2,double y2,double x,double y){
25     return (x2-x1)*(y-y1)-(x-x1)*(y2-y1);//叉积
26 }
27 bool check(double x1,double y1,double x2,double y2){
28 if(dis(x1,y1,x2,y2)<eps)return false;//构不成线段
29 for(int i=1;i<=n;i++){
30 if(cal(x1,y1,x2,y2,q[i].x1,q[i].y1)*cal(x1,y1,x2,y2,q[i].x2,q[i].y2)>eps)return false;//判段线段是不是相交
31 }
32 return true;
33 }
34 int main(  )  {
35       int T;
36       scanf("%d",&T);
37       while(T--){
38         scanf("%d",&n);
39         for(int i=1;i<=n;i++){
40         scanf("%lf %lf %lf %lf",&q[i].x1,&q[i].y1,&q[i].x2,&q[i].y2);
41         }
42         int flag=1;
43         if(n==1)flag=0;
44         else {
45         for(int i=1;i<=n;i++){
46         for(int j=i+1;j<=n;j++){
47               if(check(q[i].x1,q[i].y1,q[j].x1,q[j].y1)||check(q[i].x1,q[i].y1,q[j].x2,q[j].y2)||check(q[i].x2,q[i].y2,q[j].x1,q[j].y1)||
48                       check(q[i].x2,q[i].y2,q[j].x2,q[j].y2)){
49                     
50                 flag=0;
51                 break;
52               }
53         }
54         if(!flag)break;
55         }
56         }  
57         if(!flag)printf("Yes!\n");
58         else printf("No!\n");
59       }
60       return 0;
61 }

猜你喜欢

转载自www.cnblogs.com/letlifestop/p/10337621.html