hdu-1086 You can Solve a Geometry Problem too(线段是否相交)

题目链接:点击打开链接

You can Solve a Geometry Problem too

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 9530    Accepted Submission(s): 4679


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
题意:给N条线段,求交点数。 多条边相交于一点算多点。

思路:基础的计算几何~。这里推荐一个博客。http://dev.gameres.com/Program/Abstract/Geometry.htm#

代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
#define N 105
struct Line
{
    double x1,y1,x2,y2;
} line[N];
struct Node
{
    double x,y;
} node[4];
double ans(Node a,Node b)
{
    return a.x*b.y-a.y*b.x;
}
int check(Line a,Line b)
{
    if(!(min(a.x1,a.x2)<=max(b.x1,b.x2)&&min(a.y1,a.y2)<=max(b.y1,b.y2)&&
            min(b.x1,b.x2)<=max(a.x1,a.x2)&&min(b.y1,b.y2)<=max(a.y1,a.y2)))
        return 0;//这里是判断矩形是否相交,可以省去。
    Node p1q1,p2q1,q1p1,q2p1,q2q1,p2p1;
    p1q1.x=a.x1-b.x1;
    p1q1.y=a.y1-b.y1;
    p2q1.x=a.x2-b.x1;
    p2q1.y=a.y2-b.y1;
    q1p1.x=b.x1-a.x1;
    q1p1.y=b.y1-a.y1;
    q2p1.x=b.x2-a.x1;
    q2p1.y=b.y2-a.y1;
    q2q1.x=b.x2-b.x1;
    q2q1.y=b.y2-b.y1;
    p2p1.x=a.x2-a.x1;
    p2p1.y=a.y2-a.y1;
    if(ans(p1q1,q2q1)*ans(p2q1,q2q1)>0) return 0;
    if(ans(q1p1,p2p1)*ans(q2p1,p2p1)>0) return 0;
    return 1;
}
int main()
{
    int n,sum;
    int x1,y1,x2,y2;
    while(~scanf("%d",&n)&&n)
    {
        sum=0;
        for(int i=0; i<n; i++)
        {
            scanf("%lf %lf %lf %lf",&line[i].x1,&line[i].y1,&line[i].x2,&line[i].y2);
            for(int j=0; j<i; j++)
                if(check(line[j],line[i]))
                    sum++;
        }
        printf("%d\n",sum);
    }
    return 0;
}


你可能感兴趣的:(ACM,HDU)