直线与线段相交,枚举直线的端点 用叉积判断是否有交点
#include "cstring"
#include "iostream"
#include "algorithm"
#include "cstdio"
#include "queue"
#include "set"
#include "cmath"
using namespace std;
typedef long long LL;
const int M=510;
const int INF = 0x3f3f3f3f;
const double PI = acos(-1.00);
const double eps = 10e-8;
struct point
{
double x,y;
};
int n;
struct node
{
// struct point
// {
// double x,y;
// };
point s,t;
} s[105];
int dis(point a,point b)
{
double d;
d=sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));
if(-eps<=d && d<=eps)
return 0;
return 1;
}
double chaji(point a,point b,point c) //x1*y2-x2*y1
{
return (b.x-a.x)*(c.y-a.y)-(c.x-a.x)*(b.y-a.y);
}
double judge(point a,point b)
{
if(!dis(a,b))
return 0;
for(int i=1; i<=n; i++) //判断是否有交点
if(chaji(a, b, s[i].s)*chaji(a, b, s[i].t) > eps)
return 0;
return 1;
}
int main()
{
int t;
cin>>t;
while(t--)
{
cin>>n;
for(int i=1; i<=n; ++i)
{
cin>>s[i].s.x>>s[i].s.y>>s[i].t.x>>s[i].t.y;
}
int flag=0;
if(n==1)
flag=1;
for(int i=1; i<n; i++) //枚举线段的端点
for(int j=i+1; j<=n; j++)
if(judge(s[i].s, s[j].s)||judge(s[i].s, s[j].t)||judge(s[i].t, s[j].s)||judge(s[i].t, s[j].t))
{
flag=1;
break;
}
cout<<(flag?"Yes!":"No!")<<endl;
}
return 0;
}

本文介绍了一种通过叉积方法判断直线与线段是否相交的算法,并提供了完整的C++实现代码。该方法通过枚举线段的端点并使用叉积来判断是否存在交点。
2614

被折叠的 条评论
为什么被折叠?



