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.
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.
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
分析:
题意就是给你一些线段的端点坐标,然后判断其中有几对是相互相交的,用排斥实验判断是否在一个平面,用跨立实验判断线段是否相交;
#include<stdio.h>
struct P
{
double x0,x1,y0,y1;
} a[101];
int kuali(P a,P b)//跨立实验
{
double k1=(a.x0-b.x0)*(b.y1-b.y0)-(b.x1-b.x0)*(a.y0-b.y0);//矢量p1q1
double k2=(b.x1-b.x0)*(a.y1-b.y0)-(a.x1-b.x0)*(b.y1-b.y0);//矢量p2q1
if(k1*k2>=0)//矢量之积大于0,说明在两边
return 1;
return 0;
}
int main()
{
int n,i,j;
while(scanf("%d",&n)&&n)
{
int s=0;
for(i=0; i<n; i++)
scanf("%lf%lf%lf%lf",&a[i].x0,&a[i].y0,&a[i].x1,&a[i].y1);
for(i=0; i<n-1; i++)
for(j=i+1; j<n; j++)//验证p1p2,q1q2是否相互跨立
s+=(kuali(a[i],a[j])&&kuali(a[j],a[i]));
printf("%d\n",s);
}
return 0;
}