题目链接:http://poj.org/problem?id=1269
题目大意:给出四个点的坐标x1,y1,x2,y2,x3,y3,x4,y4,前两个形成一条直线,后两个坐标形成一条直线。然后问你是否平行,重叠或者相交,如果相交,求出交点坐标。
算法:二维几何直线相交+叉积
解法:先用叉积判断是否相交,如果相交的话,设交点坐标为p0(x0,y0)。向量(p0p1)和(p0p2)的叉积为0,有(x1-x0)*(y2-y0)-(y1-y0)*(x2-x0)=0;同理,求出p0和p3p4直线的式子。然后联立求解x0,y0。平行或重叠的情况就自己YY了。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<algorithm>
#define inf 0x7fffffff
#define exp 1e-10
#define PI 3.141592654
using namespace std;
struct Point
{
double x,y;
Point(double x=,double y=):x(x),y() {}
};
typedef Point Vector;
double cross(Vector A,Vector B)
{
return A.x*B.y-A.y*B.x;
}
Point GetLineIntersection(Point P,Vector v,Point Q,Vector w)
{
Point uu;
Vector u=Point(P.x-Q.x , P.y-Q.y);
double t=cross(w,u)/cross(v,w);
uu.x=P.x+v.x*t;
uu.y=P.y+v.y*t;
return uu;
}//调用训练指南上这个函数怎么错了,我写错了吗
int main()
{
int n;
double x1,y1,x2,y2,x3,y3,x4,y4;
//cin>>n;
while (cin>>n)
{
printf("INTERSECTING LINES OUTPUT\n");
while (n--) {
cin>>x1>>y1>>x2>>y2>>x3>>y3>>x4>>y4;
Point P,Q;
P.x=x1 ;P.y=y1 ;
Q.x=x3 ;Q.y=y3 ;
Vector v,w;
v.x=x2-x1 ;v.y=y2-y1;
w.x=x4-x3 ;w.y=y4-y3;
if (cross(v,w)!=)
{
//Vector vv=GetLineIntersection(P,v,Q,w);
double a1,b1,c1;
double a2,b2,c2;
a1=y1-y2 ;b1=x2-x1 ;c1=x1*y2-y1*x2;
a2=y3-y4 ;b2=x4-x3 ;c2=x3*y4-y3*x4;
double x0=(b1*c2-b2*c1)/(b2*a1-b1*a2);
double y0=(a2*c1-a1*c2)/(a1*b2-a2*b1);
printf("POINT %.2f %.2f\n",x0,y0);
}
else
{
if (fabs(v.x)<=exp && fabs(w.x)<=exp)
{
if (fabs(x1-x3)<=exp)
printf("LINE\n");
else printf("NONE\n");
}
else if (fabs(v.y)<=exp && fabs(w.y)<=exp)
{
if (fabs(y1-y3)<=exp)
printf("LINE\n");
else printf("NONE\n");
}
else
{
if (fabs((y3-w.y/w.x*x3)-(y1-w.y/w.x*x1))<=exp)
printf("LINE\n");
else printf("NONE\n");
}
}
}
printf("END OF OUTPUT\n");
}
return ;
}