HDU 1086 You can Solve a Geometry Problem too(判定线段相交 规范相交和非规范相交)

HDU 1086 You can Solve a Geometry Problem too(判定线段相交)

http://acm.hdu.edu.cn/showproblem.php?pid=1086

题意:

       给你n条线段,要你输出这些线段一共有多少交点? 如果多线共点,那么就该点算多次.

分析:

       直接枚举两两线段,如果它们相交,就交点数+1即可.下面说说如何判断两条线段相交呢?

       两条线段相交可能存在两种情况,

       规范相交: 交点在线段内部(不在任何一条线段的端点上).

       非规范相交: 交点在某条线段的端点.

       对于规范相交,我们可以用叉积来判断,简单来说就是”每条线段的两个端点都在另一条线段的两端(这里的两端指的是叉积的符号不同)”详见刘汝佳<<训练指南>>P258.

       对于非规范相交,我们只要判断一条线段的某个端点是否在另外一条线段上即可.

       具体还是看代码比较方便.

#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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值