You can Solve a Geometry Problem too(计算多个线段的交点个数)

来源:互联网 发布:数据库 代码 编辑:程序博客网 时间:2024/06/02 00:21

You can Solve a Geometry Problem too

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


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
20.00 0.00 1.00 1.000.00 1.00 1.00 0.0030.00 0.00 1.00 1.000.00 1.00 1.00 0.0000.00 0.00 1.00 0.000
 

Sample Output
13
 

Author
lcy
 

#include<cstdio>#include<iostream>#include<cstring>using namespace std;typedef struct point{    float x;    float y;}Point;//判断直线AB是否与线段CD相交bool lineIntersectSide(Point A, Point B, Point C, Point D){    // A(x1, y1), B(x2, y2)的直线方程为:    // f(x, y) =  (y - y1) * (x1 - x2) - (x - x1) * (y1 - y2) = 0    float fC = (C.y - A.y) * (A.x - B.x) - (C.x - A.x) * (A.y - B.y);    float fD = (D.y - A.y) * (A.x - B.x) - (D.x - A.x) * (A.y - B.y);    if(fC * fD > 0)        return false;    return true;}bool sideIntersectSide(Point A, Point B, Point C, Point D){    if(!lineIntersectSide(A, B, C, D))        return false;    if(!lineIntersectSide(C, D, A, B))        return false;    return true;}int main(){    int n,num,i,j;    Point p[105][2];    while(cin>>n,n)    {        num=0;        for(i=0;i<n;i++)        {            for(j=0;j<2;j++)            {                cin>>p[i][j].x>>p[i][j].y;            }        }        for(i=0;i<n;i++)        {            for(j=i+1;j<n;j++)            {                if(sideIntersectSide(p[i][0],p[i][1],p[j][0],p[j][1]))                {                    num++;                }            }        }        cout<<num<<endl;    }}


0 0