You can Solve a Geometry Problem tooTime Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 8964 Accepted Submission(s): 4375
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
Sample Output
Author
lcy
|
题意:给定线段两端坐标计算这些线段的交点个数可以重复计算
解题思路:枚举每两条线段计算交点
#include<cstdio>
#include<cstdlib>
#include<cstring>
#define eps 1e-10
using namespace std;
double MAX(double a,double b){return a>b?a:b;
}
double MIN(double a,double b){return a<b?a:b;
}
struct point{double x,y;
};
struct line{point a,b;
}A[110];
bool judge(int a,int b){ if(MIN(A[a].a.x,A[a].b.x)>MAX(A[b].a.x,A[b].b.x)||MIN(A[a].a.y,A[a].b.y)>MAX(A[b].a.y,A[b].b.y)||MIN(A[b].a.x,A[b].b.x)>MAX(A[a].a.x,A[a].b.x)||MIN(A[b].a.y,A[b].b.y)>MAX(A[a].a.y,A[a].b.y)) return false; double h,i,j,k; h=(A[a].b.x-A[a].a.x)*(A[b].a.y-A[a].a.y)-(A[a].b.y-A[a].a.y)*(A[b].a.x-A[a].a.x); i=(A[a].b.x-A[a].a.x)*(A[b].b.y-A[a].a.y)-(A[a].b.y-A[a].a.y)*(A[b].b.x-A[a].a.x); j=(A[b].b.x-A[b].a.x)*(A[a].a.y-A[b].a.y)-(A[b].b.y-A[b].a.y)*(A[a].a.x-A[b].a.x); k=(A[b].b.x-A[b].a.x)*(A[a].b.y-A[b].a.y)-(A[b].b.y-A[b].a.y)*(A[a].b.x-A[b].a.x); return h*i<=eps&&j*k<=eps;
}
int main()
{int n,i,j,k,ans;while(scanf("%d",&n),n){for(i=0;i<n;++i){scanf("%lf%lf%lf%lf",&A[i].a.x,&A[i].a.y,&A[i].b.x,&A[i].b.y);}ans=0;for(i=0;i<n;++i){for(j=i+1;j<n;++j){if(judge(i,j))ans++;}}printf("%d\n",ans);}return 0;
}