POJ 1269 Intersecting Lines(直线相交的判断)

点击打开链接

题意就是, 给你8个点, (x1, y1),( x2, y2), (x3, y3), (x4, y4);

判断这两个直线相交, 平行, 还是重合, 相交输出交点, 平行输出NONE, 重合是LINE;

设直线PQ, 他的方向向量是w = (p0 - q0), 直线上一点是p0,则直线 可 表示为 PQ = p0 + vw* t;若是直线t为0;

设直线MN,同上, MN = m0 + v * t

设向量u = p0 - m0;

tt = Cross(w, u )/ Cross(v, u);

则交点就是  p0.x + v.x * tt,       p0.y + v.y * tt;

证明略

code

#include <cstdio>
#include <cmath>
#include <iostream>
#include <algorithm>
using namespace std;
#define eps 1e-8
double x1, xy1, x2, y2, x3, y3, x4, y4;
void judge();
int Cross(double x,double y,double xx1,double yy1,double xx2,double yy2);
bool parallel(); //判断是否平行
void IntersectionSection();//判断是否相交 和 计算交点

int main()
{
	int n;
	cin >> n;
	printf("INTERSECTING LINES OUTPUT\n");
	while(n--)
	{
		cin >> x1 >> xy1 >> x2 >> y2 >> x3 >> y3 >> x4 >> y4;
		judge();
		
	}printf("END OF OUTPUT\n");
	return 0;
}

void judge()
{
	if((x1 == x2 && x2 == x3 && x3 == x4 ) ||
		(xy1 == y2 && y2 == y3 && y3== y4))
	{
		printf("LINE\n");
		return ;
	}
	if((x1==x2 && x3==x4) || (xy1==y2 && y3 == y4))
	{
		printf("NONE\n");
		return ;
	}
	if( parallel() )
	{
		if(!Cross(x1, xy1, x3, y3, x4, y4))
			   printf("LINE\n");
		else printf("NONE\n");
		return;
	}
	IntersectionSection();
}

bool parallel()
{
	double px = x2 - x1, py = y2 - xy1,
	qx = x4 - x3, qy = y4 - y3;
//	printf("paralle %lf %lf\n", py/px, qy/qx);
	if(fabs((py/px) - (qy/qx)) < eps)
		return true;
	return false;
}

int Cross(double x,double y,double xx1,double yy1,double xx2,double yy2)
{
	//printf("%d %d %d %d %d %d\n", A.x, A.y, B.x1, B.y1, B.x2, B.y2);
	double Px = x - xx1,Py = y - yy1, Qx = xx2 - xx1, Qy = yy2 - yy1;
	//printf("Cross%f %f %f %f %f\n",Px, Py, Qx, Qy,  Px*Qy - Qx*Py);
	return Px*Qy - Qx*Py;   //<0, left, >0 right
}

void IntersectionSection()
{
	/*if(Cross(x1, xy1, x3,  y3, x4, y4) * Cross(x2, y2, x3, y3, x4, y4) >= eps
	|| Cross(x3, y3, x1, xy1, x2, y2) * Cross(x4, y4, x1, xy1, x2, y2) >= eps)
	{
		printf("###NONE\n");
		return;
	}*/
	double px = x1, py = xy1, vx = x2 - x1, vy = y2 - xy1,
	qx = x3, qy = y3, wx = x4 - x3, wy = y4 - y3,
	ux = px - qx, uy = py - qy, t;
	t = (wx*uy - ux*wy)/(vx*wy - wx*vy);

	printf("POINT %.2f %.2f\n", px + t*vx, py+t*vy);
}



你可能感兴趣的:(intersect)