HDU-1086-You can Solve a Geometry Problem too

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


题中输入的就是两点的坐标,所以我们用这两点的坐标来求直线方程

已知两点(x1,y1) , (x2,y2)

代入两点公式: (x-x1)/(x2-x1)=(y-y1)/(y2-y1)

整理可得方程: H = x * (y2 - y1 ) - y * ( x2 - x1 )  - x1 * y2 + x2 * y1;

然后将另一条线段的两个端点分别带入方程中 可计算出一个结果 (有正负性),在直线上方的点带入方程会得到一个正值,而在直线下方的点带入方程会得到一个负值,so。。。只要两个值异号便可说明这两条线线段有交点。

需要注意的是:要分别判断,意思就是有两条线段 a,b 既要判断 b的两个端点是否在a的两侧,还要判断a的两个端点是否在b的两个端点。。就OK 了。。

PS:感谢轩仔。。




#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
using namespace std;

struct node
{
    double x;
    double y;
} a[200],b[200];

int pd ( node a1, node b1,node a2,node b2)
{
    double h1 = a2.x*(b1.y - a1.y) - a2.y*(b1.x-a1.x) - a1.x*b1.y + b1.x*a1.y;
    double h2 = b2.x*(b1.y - a1.y) - b2.y*(b1.x-a1.x) - a1.x*b1.y + b1.x*a1.y;

    //printf ("%lf  %lf\n",h1,h2);
    if ( h1 * h2 <= 0)
    {
        return 1;
    }
    else
        return 0;
}

int main ()
{
    int n;
    while (~scanf ("%d",&n)&&n)
    {
        int sum = 0;
        for (int i = 0; i < n; i++)
        {
            scanf ("%lf%lf%lf%lf",&a[i].x,&a[i].y,&b[i].x,&b[i].y);
        }

        for (int i = 0 ; i < n; i++)
        {
            for (int j = i + 1; j < n; j++)
            {
                if (pd(a[i],b[i],a[j],b[j]) && pd (a[j],b[j],a[i],b[i]))
                {
                    sum++;
                }
            }
        }
        printf ("%d\n",sum);
    }
    return 0;
}




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值