求多条线段相交(暴力了点)





#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;
}


阅读更多
文章标签: struct c
上一篇判断线段相交
下一篇Area
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭