关闭

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

284人阅读 评论(0) 收藏 举报





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


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:147346次
    • 积分:1542
    • 等级:
    • 排名:千里之外
    • 原创:92篇
    • 转载:8篇
    • 译文:2篇
    • 评论:1条
    最新评论