【题目来源】:https://vjudge.net/problem/POJ-1269
【题意】
给出两条直线的起、终点坐标,试求两条直线是相交,平行,还是重合?若是相交,则求出交点。
【思路】
用一般的模板:(转自:Rachel-Zhang)
直线的一般方程为F(x) = ax + by + c = 0。既然我们已经知道直线的两个点,假设为(x0,y0), (x1, y1),那么可以得到a = y0 – y1, b = x1 – x0, c = x0y1 – x1y0。
因此我们可以将两条直线分别表示为
F0(x) = a0*x + b0*y + c0 = 0, F1(x) = a1*x + b1*y + c1 = 0
那么两条直线的交点应该满足
a0*x + b0*y +c0 = a1*x + b1*y + c1
由此可推出
x = (b0*c1 – b1*c0)/D
y = (a1*c0 – a0*c1)/D
D = a0*b1 – a1*b0, (D为0时,表示两直线平行或者重合)
【代码】
#include<cmath>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long LL;
const double esp=1e-5;
int n;
int x,y,x2,y2,x3,y3,x4,y4;
double check(int p,int q)
{
return (x-x2)*1.0*(q-y2)*1.0-(p-x2)*1.0*(y-y2)*1.0;
}
int main()
{
while(~scanf("%d",&n))
{
puts("INTERSECTING LINES OUTPUT");
for(int i=1; i<=n; i++)
{
scanf("%d%d%d%d%d%d%d%d",&x,&y,&x2,&y2,&x3,&y3,&x4,&y4);
int a1=y-y2,a2=y3-y4;
int b1=x2-x,b2=x4-x3;
int c1=x*y2-x2*y,c2=x3*y4-x4*y3;
int D=a1*b2-a2*b1;
if(D==0)//若D为0,则两直线平行或重合
{
if(fabs(check(x3,y3)-0.0)<esp&&fabs(check(x4,y4)-0.0)<esp)//利用叉积验证是否重合
{
printf("LINE\n");
}
else
printf("NONE\n");
}
else//若不是重合或者平行,那么两条直线必定是相交
{
double p=(b1*c2-b2*c1)*1.0/(D*1.0);
double q=(a2*c1-a1*c2)*1.0/(D*1.0);
if(p<0.0&&0.0-p<esp)//试了一组数据:0 0 0 2 0 0 1 0,结果会出现-0.00 -0.00的情况(但是也对)
p=-p;
if(q<0.0&&0.0-q<esp)
q=-q;
printf("POINT %.2lf %.2lf\n",p,q);
}
}
puts("END OF OUTPUT");
}
}