# 求多条线段相交（暴力了点）



#include<stdio.h>
#include<math.h>
struct point
{
double x,y;
};
struct line
{
point a,b;
}g[120];
double MAX(double a,double b)
{
return a>b?a:b;
}
double MIN(double a,double b)
{
return a<b?a:b;
}
double cross_segment(point a,point b,point c)
{
return (c.x-a.x)*(b.y-a.y)-(b.x-a.x)*(c.y-a.y);
}
int onsegment(point a,point b,point c)
{
double d1=MIN(a.x,b.x);
double d2=MAX(a.x,b.x);
double d3=MIN(a.y,b.y);
double d4=MAX(a.y,b.y);
if(d1<=c.x&&d2>=c.x&&d3<=c.y&&d4>=c.y)
return 1;
return 0;
}
int segments(line a,line b)
{
double d1=cross_segment(b.a,b.b,a.a);
double d2=cross_segment(b.a,b.b,a.b);
double d3=cross_segment(a.a,a.b,b.a);
double d4=cross_segment(a.a,a.b,b.b);
if(((d1>0&&d2<0)||(d1<0&&d2>0))&&((d3>0&&d4<0)||(d3<0&&d4>0)))
return 1;
else if(d1==0&&onsegment(b.a,b.b,a.a))
return 1;
else if(d2==0&&onsegment(b.a,b.b,a.b))
return 1;
else if(d3==0&&onsegment(a.a,a.b,b.a))
return 1;
else if(d4==0&&onsegment(a.a,a.b,b.b))
return 1;
else
return 0;
}

int main()
{
int i,j,k,m,n,ncase,sum;
while(scanf("%d",&m),m)
{

for(i=0;i<m;i++)
scanf("%lf%lf%lf%lf",&g[i].a.x,&g[i].a.y,&g[i].b.x,&g[i].b.y);
sum=0;
if(m==1)
{
printf("0\n");
continue;
}
for(i=0;i<m;i++)
{
for(j=i+1;j<m;j++)
{
if(segments(g[i],g[j]))
sum++;
}
}
printf("%d\n",sum);
}
return 0;
}

#### N条线段求交的扫描算法

2017-10-01 21:17:13

#### 【计算几何】求线段相交交点坐标

2017-03-04 10:57:00

#### 计算几何----判断线段相交（一）

2016-04-07 22:54:27

#### 计算几何---判断线段相交（二）

2016-04-07 22:59:32

#### C++ 实现两线段是否相交、相交情况、若相交求出交点坐标

2015-05-11 20:32:05

#### 判断两线段相交，并求交点

2017-11-20 10:55:17

#### POJ 1127 基础计算几何（判断两线段相交）+并查集

2017-07-15 16:03:51

#### 线段相交交点个数

2018-06-04 21:17:22

#### POJ 1127 —— 计算几何 && 线段相交

2013-10-22 20:01:46

#### 计算几何之判断线段相交

2016-08-11 11:26:49