HDU_1086 You can solve a geometry problem too(计算几何)

Problem Description

Many geometry(几何)problems were designed in the ACM/ICPC. And now, I also prepare a geometry problem for this final exam. According to the experience of many ACMers, geometry problems are always much trouble, but this problem is very easy, after all we are now attending an exam, not a contest :)
Give you N (1<=N<=100) segments(线段), please output the number of all intersections(交点). You should count repeatedly if M (M>2) segments intersect at the same point.

**Note:
You can assume that two segments would not intersect at more than one point.**

Input

Input contains multiple test cases. Each test case contains a integer N (1=N<=100) in a line first, and then N lines follow. Each line describes one segment with four float values x1, y1, x2, y2 which are coordinates of the segment’s ending.
A test case starting with 0 terminates the input and this test case is not to be processed.

Output

For each case, print the number of intersections, and one line one case.

Sample Input

2
0.00 0.00 1.00 1.00
0.00 1.00 1.00 0.00
3
0.00 0.00 1.00 1.00
0.00 1.00 1.00 0.000
0.00 0.00 1.00 0.00
0

Sample Output

1
3

解题思路:

说实话,这条题目用不到算法,难点在于如何判断两条线段相交。

本题通过 跨立实验 来判断两条线段是否相交,其中用到的知识点主要有 向量叉乘(具体可见:https://baike.baidu.com/item/%E5%90%91%E9%87%8F%E7%A7%AF/4601007?fr=aladdin)。

假设两条直线A((a.x,a.y) , (b.x,b.y)) B((c.x,c.y) , (d.x , d.y))
首先判断 点 a , b 是否 在线段 B 的 两侧。
1.计算 向量 ca = ( (c.x - a.x) , (c.y - a.y) ) , 向量 cb = ( (c.x - b.x) , (c.y - b.y) ) , 向量 cd = ( (c.x - d.x) , (c.y - d.y) ) .
2.计算 向量ca 与 向量cd 的叉乘:
因为原则上向量叉乘适用于空间向量 ,所以先将 向量ca 与 向量cd 变为空间向量 (z轴都置 0)。
利用公式:这里写图片描述
就可以计算得出结果了 。代码中 interaction 函数中的 u , v, w ,z 就是用量存放计算结果的 ,注意:本题叉乘结果因为只有1维不是0 , 所以结果直接取得数值。

至于为什么可以利用这个(u*v<=0.00000001 && w*z<=0.00000001)判断两点两点是否在线段两侧直接看上面给的百度百科里面的讲解就可以了。

代码:

#include <stdio.h>
using namespace std;

typedef struct{
    float x;
    float y;
}Point;

int interaction(Point a , Point b ,Point c ,Point d){
    float u , v, w ,z;
    u=(c.x-a.x)*(b.y-a.y)-(b.x-a.x)*(c.y-a.y);
    v=(d.x-a.x)*(b.y-a.y)-(b.x-a.x)*(d.y-a.y);
    w=(a.x-c.x)*(d.y-c.y)-(d.x-c.x)*(a.y-c.y);
    z=(b.x-c.x)*(d.y-c.y)-(d.x-c.x)*(b.y-c.y);
    if(u*v<=0.00000001 && w*z<=0.00000001)
        return 1;
    return 0;
}

Point p[105][2];

int main(){
    int n , i , j , sum = 0;
    while(scanf("%d",&n) != EOF){
        sum = 0;
        if (n == 0)
            break;
        for(i = 0 ; i < n ; i ++)
            scanf("%f %f %f %f",&p[i][0].x,&p[i][0].y,&p[i][1].x,&p[i][1].y);

        for(i = 0 ; i < n ; i ++)
            for( j = i+1 ; j < n ; j ++){
                if(interaction(p[i][0] , p[i][1] , p[j][0] , p[j][1]))
                    sum ++;
            }

        printf("%d\n",sum );
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值