点的结构
struct point
{
double x,y;
point(){}
point(double _x,double
线段的结构
struct egde
{
point start,end;//
egde(){}
egde(point a,point b){
start=a;end=b;}
};//建立的边,存在的线段
求两直线(线段)交点
void getPoint(point p1,point p2,point p3 point p4)
{
double a0,b0,c0,a1,b1,c1;
a0=p1.y-p2.y,b0=p2.x-p1.x,c0=p1.x*p2.y-p2.x*p1.y;
a1=p3.y-p4.y,b1=p4.x-p3.x,c1=p3.x*p4.y-p4.x*p3.y;
double D=a0*b1-a1*b0;
if(fabs(D)<e)
{
if(fabs(cross(v(p1,p3),v(p1,p2)))<e) printf("coincidence\n");
else printf("parallel\n");
}
else
{
double x=(b0*c1-b1*c0)/D;
double y=(a1*c0-a0*c1)/D;
printf("POINT %.2f %.2f\n",x,y);//输出%.2lf与%.2f的区别?输出不用lf
}
}
判断两线段相交
注意:不能判断共线,共端点情况情况。
double multi(point p1,point p2,point p0)
{
return (p1.x-p0.x)*(p2.y-p0.y)-(p2.x-p0.x)*(p1.y-p0.y);
}
bool intAcross(egde v1,egde v2)
{
if(max(v1.start.x,v1.end.x)>=min(v2.start.x,v2.end.x)&&
max(v2.start.x,v2.end.x)>=min(v1.start.x,v1.end.x)&&
max(v1.start.y,v1.end.y)>=min(v2.start.y,v2.end.y)&&
multi(v2.start,v1.end,v1.start)*multi(v1.end,v2.end,v1.start)>0&&
multi(v1.start,v2.end,v2.start)*multi(v2.end,v1.end,v2.start)>0) return 1;//相交+规范相交
return 0;
判断线段相交
可以有共端点的情况
bool Across(egde v1,egde v2)
{
if(multi(v1.start,v2.start,v1.end)*multi(v1.start,v2.end,v1.end)<eps&&
multi(v2.start,v1.start,v2.end)*multi(v2.start,v1.end,v2.end)<eps) return 1;//不是规范相交可以交端点
return 0;
}
依旧是判断线段相交
交与一个端点也是相交,包含不算相交
int sgn(double x)
{
if(fabs(x) < eps)return 0;
if(x < 0)return -1;
else return 1;
}
//线段p1p2与线段p3p4
bool Across(point p1,point p2,point p3,point p4)
{
return
max(p1.x,p2.x) >= min(p3.x,p4.x)&&
max(p3.x,p4.x) >= min(p1.x,p2.x)&&
max(p1.y,p2.y) >= min(p3.y,p4.y)&&
max(p3.y,p4.y) >= min(p1.y,p2.y)&&
sgn(multi(p3,p1,p2))*sgn(multi(p4,p1,p2))<=0&&
sgn(multi(p1,p3,p4))*sgn(multi(p2,p3,p4))<=0;
}
求线段交点(在判断已有交点的情况使用)
//求线段交点
point intersection(egde u,egde v)
{
point p;
p.x=(multi(v.end,u.end,u.start)*v.start.x-multi(v.start,u.end,u.start)*v.end.x)/(
multi(v.end,u.end,u.start)-multi(v.start,u.end,u.start));
p.y=(multi(v.end,u.end,u.start)*v.start.y-multi(v.start,u.end,u.start)*v.end.y)/(
multi(v.end,u.end,u.start)-multi(v.start,u.end,u.start));
return p;