正文
HDU 1086You can Solve a Geometry Problem too(判断两条选段是否有交点)
小程序:扫一扫查出行
【扫一扫了解最新限行尾号】
复制小程序
【扫一扫了解最新限行尾号】
复制小程序
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1086
判断两条线段是否有交点,我用的是跨立实验法:
两条线段分别是A1到B1,A2到B2,很显然,如果这两条线段有交点,那么可以肯定的是:
A1-B1,A2-B1这两个向量分别在B2-B1的两边,判断是不是在两边可以用向量的叉积来判断,这里就不说了,同理B1-A1,B2-A1在A2-A1的两边,当同时满足这两个条件时,说明这两条线段是有交点的。
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<cmath>
using namespace std;
const int maxn = ;
const double eps = 1e-;
struct point
{
double x,y;
point(double x = ,double y = ):x(x),y(y) {}
inline friend point operator + (point p1,point p2)
{
return point(p1.x+p2.x,p1.y+p2.y);
}
inline friend point operator - (point p1,point p2)
{
return point(p1.x-p2.x,p1.y-p2.y);
}
}A[maxn],B[maxn]; inline double dot(point p1,point p2)
{
return p1.x*p2.y - p2.x*p1.y;
}
inline double dis(point p1,point p2)
{
return sqrt((p1.x-p2.x)*(p1.x-p2.x) + (p1.y-p2.y)*(p1.y-p2.y));
}
int judge(point p1,point p2,point p3,point p4)
{
double temp = dot(p3-p1,p2-p1) * dot(p4-p1,p2-p1);
if(temp < || fabs(temp) < eps) return ;
return ;
} int main()
{
//freopen("in","r",stdin);
int n;
while(scanf("%d",&n),n)
{
for(int i = ;i < n;++i)
scanf("%lf%lf%lf%lf",&A[i].x,&A[i].y,&B[i].x,&B[i].y);
int ans = ;
for(int i = ;i < n;++i)
for(int j = i+;j < n;++j)
{
if(judge(A[i],B[i],A[j],B[j]) && judge(A[j],B[j],A[i],B[i])) ans++;
}
printf("%d\n",ans);
}
return ;
}