首先说明一下这题的数据真的好水。。
#include
#include
#include
using namespace std;
double f(double x1,double y1,double x2,double y2,double x3,double y3,double x4,double y4,double x)
{
double x0,y0;
x0 = ((x2-x1)*(x4-x3)*(y3-y1)+(y2-y1)*(x4-x3)*x1-(y4-y3)*(x2-x1)*x3)/(-x);
y0 = ((y2-y1)*(y4-y3)*(x3-x1)+(x2-x1)*(y4-y3)*y1-(x4-x3)*(y2-y1)*y3)/(x);
//printf(">>%lf%lf<<\n",x0,y0);
if((x0-x1)*(x0-x2)<=0 && (x0-x3)*(x0-x4) <=0 && (y0-y1)*(y0-y2) <=0 && (y0-y3)*(y0-y4) <=0)
return 1;
else
return 0;
}
int main()
{
int n;
int i,j;
double x1[102],x2[102],y1[102],y2[102];
while (~scanf("%d",&n))
{
if(n == 0)
break;
int ans = 0;
for(i = 0 ; i < n; i++)
{
scanf("%lf%lf%lf%lf",&x1[i],&y1[i],&x2[i],&y2[i]);
}
for(i = 0; i < n ;i++)
{
for(j = i+1; j < n ;j++)
{
int d = (y2[i]-y1[i])*(x1[j]-x2[j]) - (x2[i]-x1[i])*(y1[j]-y2[j]);
// printf(">>%d<<",d);
if(d == 0)
continue;
else
{
if(f(x1[i],y1[i],x2[i],y2[i],x1[j],y1[j],x2[j],y2[j],d)&&f(x1[j],y1[j],x2[j],y2[j],x1[i],y1[i],x2[i],y2[i],d))
ans++;
}
}
}
printf("%d\n",ans);
}
// cout << "Hello world!" << endl;
return 0;
}
给代码加一下备注啊
//首先判断d = (y2-y1)(x4-x3)-(y4-y3)(x2-x1),
// 若d=0,则直线AB与CD平行或重合,
// 若d!=0,则直线AB与CD有交点,设交点为E(x0,y0):
// x0 = [(x2-x1)*(x4-x3)*(y3-y1)+(y2-y1)*(x4-x3)*x1-(y4-y3)*(x2-x1)*x3]/d
//y0 = [(y2-y1)*(y4-y3)*(x3-x1)+(x2-x1)*(y4-y3)*y1-(x4-x3)*(y2-y1)*y3]/(-d)
/* 求出交点后在判断交点是否在线段上,即判断以下的式子:
(x0-x1)*(x0-x2) <=0
(x0-x3)*(x0-x4) <=0
(y0-y1)*(y0-y2) <=0
(y0-y3)*(y0-y4) <=0
只有上面的四个式子都成立才可判定(x0,y0)是线段AB与CD的交点,否则两线段无交点*/