hdu/hdoj 1086 You can Solve a Geometry Problem too

本文提供了一种用于判断两条线段是否相交的有效算法,并附带完整的C++实现代码。该算法通过计算向量乘积来判断线段的位置关系,进而确定是否相交。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

计算两条线段是否相交


推荐计算几何文章http://dev.gameres.com/Program/Abstract/Geometry.htm#判断两线段是否相交



#include <iostream>  
using namespace std;  
 
struct line 
{  
    double x1,y1,x2,y2;  
}ln[105];  
 
int n;
 
int mul(double a, double b, double c, double d)  
{  
    return a * d - b * c;  
}
 
bool judge(int i, int j)
{
    double a = mul(ln[i].x1-ln[j].x1, ln[i].y1-ln[j].y1, ln[j].x2-ln[j].x1, ln[j].y2-ln[j].y1);
    double b = mul(ln[i].x2-ln[j].x1, ln[i].y2-ln[j].y1, ln[j].x2-ln[j].x1, ln[j].y2-ln[j].y1);
    double c = a * b;
 
    double d = mul(ln[j].x1-ln[i].x1, ln[j].y1-ln[i].y1, ln[i].x2-ln[i].x1, ln[i].y2-ln[i].y1);
    double e = mul(ln[j].x2-ln[i].x1, ln[j].y2-ln[i].y1, ln[i].x2-ln[i].x1, ln[i].y2-ln[i].y1);
    double f = d * e;
 
    if(c <= 0 && f <= 0)
        return 1;
    else
        return 0;
}
 
 
int main()  
{  
 
    while(scanf("%d", &n) && n)  
    {  
        for(int i=1; i<=n; ++i)  
            scanf("%lf %lf %lf %lf", &ln[i].x1, &ln[i].y1, &ln[i].x2, &ln[i].y2);  
        int count=0;  
        for(int i=1; i<n; ++i)  
        {  
            for(int j=i+1; j<=n; ++j)  
                if(judge(i,j)) 
                    ++count;  
        }  
        cout << count << endl;  
    }  
    return 0;  
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值