hdu 1086 You can Solve a Geometry Problem too(线段相交点的个数)

题目地址

题目大意:给定n条线段,求共有多少个交点(交点重复时算多个)

解题思路:用差乘判断线段是否相交(一条线段的两个点分别与另外一条线段的差乘相乘<=0,则相交)

#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <cstring>
#include <queue>
#include <string>
#include <map>
#include <stack>
#include <list>
#include <set>

using namespace std;

const int maxn = 100+10;
const double eps = 1e-10;

struct Point
{
    double x;
    double y;
    Point(double x = 0, double y = 0) : x(x),y(y){}
}point1[maxn],point2[maxn];

typedef Point Vector;

Vector operator - (Point A, Point B) 
{
    return Vector(A.x-B.x, A.y-B.y);
}

double Cross(Vector A,Vector B)
{
    return A.x * B.y - A.y * B.x;
}

int dcmp(double x)
{
    if(fabs(x) < eps)
        return 0;
    else
        return x > 0 ? 1 : -1;
}

bool SegmentProperIntersection(Point A,Point B,Point C,Point D)
{
    double c1 = Cross(B-A,C-A);
    double c2 = Cross(B-A,D-A);
    double c3 = Cross(D-C,A-C);
    double c4 = Cross(D-C,B-C);
    return dcmp(c1) * dcmp(c2) <= 0 && dcmp(c3) * dcmp(c4) <= 0;
}

int main()
{
    int n;
    int tot;
    while(scanf("%d",&n) != EOF && n)
    {
        for(int i = 0; i < n; i++)
            scanf("%lf%lf%lf%lf",&point1[i].x,&point1[i].y,&point2[i].x,&point2[i].y);
        tot = 0;
        for(int i = 0; i < n ; i++)
        {
            for(int j = i+1; j < n; j++)
            {
                if(SegmentProperIntersection(point1[i],point2[i],point1[j],point2[j]))
                    tot++;
            }
        }
        printf("%d\n",tot);
    }
    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值