HDU 1086 You can Solve a Geometry Problem too(判定线段相交)
http://acm.hdu.edu.cn/showproblem.php?pid=1086
题意:
给你n条线段,要你输出这些线段一共有多少交点? 如果多线共点,那么就该点算多次.
分析:
直接枚举两两线段,如果它们相交,就交点数+1即可.下面说说如何判断两条线段相交呢?
两条线段相交可能存在两种情况,
规范相交: 交点在线段内部(不在任何一条线段的端点上).
非规范相交: 交点在某条线段的端点.
对于规范相交,我们可以用叉积来判断,简单来说就是”每条线段的两个端点都在另一条线段的两端(这里的两端指的是叉积的符号不同)”详见刘汝佳<<训练指南>>P258.
对于非规范相交,我们只要判断一条线段的某个端点是否在另外一条线段上即可.
具体还是看代码比较方便.
AC代码:
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
const int maxn=100+5;
const double eps= 1e-10;
int dcmp(double x)
{
if(fabs(x)<eps) return 0;
return x<0?-1:1;
}
struct Point
{
double x,y;
Point(){}
Point(double x,double y):x(x),y(y){}
};
typedef Point Vector;
Vector operator-(Point A,Point B)
{
return Vector(A.x-B.x,A.y-B.y);
}
double Dot(Vector A,Vector B)
{
return A.x*B.x+A.y*B.y;
}
double Cross(Vector A,Vector B)
{
return A.x*B.y-A.y*B.x;
}
bool InSegment(Point P,Point a1,Point a2)
{
return dcmp(Cross(a2-P,a1-P))==0 && dcmp(Dot(a2-P,a1-P))<=0;
}
bool SegmentIntersection(Point a1,Point a2,Point b1,Point b2)
{
double c1=Cross(a2-a1,b1-a1),c2=Cross(a2-a1,b2-a1);
double c3=Cross(b2-b1,a1-b1),c4=Cross(b2-b1,a2-b1);
if( dcmp(c1)*dcmp(c2)<0 && dcmp(c3)*dcmp(c4)<0 ) return true;
if( dcmp(c1)==0 && InSegment(b1,a1,a2) ) return true;
if( dcmp(c1)==0 && InSegment(b2,a1,a2) ) return true;
if( dcmp(c3)==0 && InSegment(a1,b1,b2) ) return true;
if( dcmp(c4)==0 && InSegment(a2,b1,b2) ) return true;
return false;
}
Point P[maxn],Q[maxn];
int main()
{
int n;
while(scanf("%d",&n)==1 && n)
{
int ans=0;
for(int i=1;i<=n;++i)
scanf("%lf%lf%lf%lf",&P[i].x,&P[i].y,&Q[i].x,&Q[i].y);
for(int i=1;i<=n;++i)
for(int j=i+1;j<=n;++j)
if(SegmentIntersection(P[i],Q[i],P[j],Q[j]))
++ans;
printf("%d\n",ans);
}
return 0;
}