天天看点

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

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)。

利用公式:

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

就可以计算得出结果了 。代码中 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<= && w*z<=)
        return ;
    return ;
}

Point p[][];

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

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

        printf("%d\n",sum );
    }
    return ;
}