原理:
共线:
由叉积的原理知道如果p1,p2,p3共线的话那么(p2-p1)X(p3-p1)=0。因此如果p1,p2,p3共线,p1,p2,p4共线,那么两条直线共线。叉积为0说明共线。
平行:
由向量可以判断出两直线是否平行。如果两直线平行,那么向量p1p2、p3p4也是平等的。即((p1.x-p2.x)(p3.y-p4.y)-(p1.y-p2.y)(p3.x-p4.x))==0说明向量平行。
如何求出交点?
这里也用到叉积的原理。假设交点为p0(x0,y0)。则有:
(p1-p0)X(p2-p0)=0
(p3-p0)X(p2-p0)=0
展开后即是
(y1-y2)x0+(x2-x1)y0+x1y2-x2y1=0
(y3-y4)x0+(x4-x3)y0+x3y4-x4y3=0
将x0,y0作为变量求解二元一次方程组。
假设有二元一次方程组
a1x+b1y+c1=0;
a2x+b2y+c2=0;
那么
x=(c1b2-c2b1)/(a2b1-a1b2);
y=(a2c1-a1c2)/(a1b2-a2b1);
因为此处两直线不会平行,所以分母不会为0。//就是斜率,已懂
板子
#include <iostream>
#include <string.h>
#include <stdio.h>
#include <algorithm>
#include <math.h>
#include <queue>
#define inf 0x3f3f3f3f
#define eps 1e-9
typedef long long ll;
using namespace std;
int n;
struct Point
{
double x,y;
};
struct Line
{
Point a,b;
} line[3];
double xmult(Point p1,Point p2,Point p)//叉积,等于0说明p1,p2,p共线
{
return (p1.x-p.x)*(p2.y-p.y)-(p1.y-p.y)*(p2.x-p.x);
}
int parallel(Line u,Line v)//等于0说明向量平行
{
return ((u.a.x-u.b.x)*(v.a.y-v.b.y)-(v.a.x-v.b.x)*(u.a.y-u.b.y));
}
Point intersection(Line u,Line v)//求交点
{
Point ret=u.a;
double t=((u.a.x-v.a.x)*(v.a.y-v.b.y)-(u.a.y-v.a.y)*(v.a.x-v.b.x))/((u.a.x-u.b.x)*(v.a.y-v.b.y)-(u.a.y-u.b.y)*(v.a.x-v.b.x));
ret.x+=(u.b.x-u.a.x)*t;
ret.y+=(u.b.y-u.a.y)*t;
return ret;
}
int main()
{
while(scanf("%d",&n)!=EOF)
{
cout<<"INTERSECTING LINES OUTPUT"<<endl;
for(int i=0; i<n; i++)
{
scanf("%lf%lf%lf%lf%lf%lf%lf%lf",&line[1].a.x,&line[1].a.y,&line[1].b.x,&line[1].b.y,&line[2].a.x,&line[2].a.y,&line[2].b.x,&line[2].b.y);
if(fabs(parallel(line[1],line[2]))<=eps&&fabs(xmult(line[1].a,line[1].b,line[2].a))<=eps)
{
printf("LINE\n");
}
else if(fabs(parallel(line[1],line[2]))<=eps)
{
printf("NONE\n");
}
else
{
Point tt=intersection(line[1],line[2]);
printf("POINT %.2f %.2f\n", tt.x,tt.y);//poj只能输出f
}
}
printf("END OF OUTPUT\n");
}
return 0;
}