题解
- 两直线ab和cd平行:ab×cd = 0
- 两直线重合:在平行的基础上满足ac×ad = 0
- 否则求交点。
代码
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <vector>
using namespace std;
double const eps = 1e-12;
int n;
typedef struct Point{
double x,y;
Point(){};
Point(double x,double y):x(x),y(y){};
Point operator - (const Point& e)const{ //减
return Point(x - e.x,y - e.y);
}
Point operator + (const Point& e)const{ //减
return Point(x + e.x,y + e.y);
}
double operator ^ (const Point& e)const{ //叉乘
return x * e.y - y * e.x;
}
}Vector;
struct Line{
Point a,b;
}line1,line2;
int dcmp(double x){
if(fabs(x) < eps) return 0;
else return x < 0 ? -1 : 1;
}
int Judge(Line line1,Line line2){
if(dcmp((line1.b - line1.a) ^ (line2.b - line2.a)) == 0){ //平行
if(dcmp((line2.a - line1.a) ^ (line2.b - line1.a)) == 0) return 1; //重合
else return 2;
}else return 3;
}
void intersection(Point p,Vector v,Point q,Vector w){ //两直线(p+tv)和(q+tw)求交点
Vector u = p - q;
double t = (w ^ u) / (v ^ w);
Point ans = p + Point(v.x * t,v.y * t);
printf("POINT %.2f %.2f\n",ans.x,ans.y);
}
int main(){
scanf("%d",&n);
printf("INTERSECTING LINES OUTPUT\n");
for(int i=1;i<=n;i++){
scanf("%lf%lf%lf%lf",&line1.a.x,&line1.a.y,&line1.b.x,&line1.b.y);
scanf("%lf%lf%lf%lf",&line2.a.x,&line2.a.y,&line2.b.x,&line2.b.y);
int flag = Judge(line1,line2);
if(flag == 1) printf("LINE\n");
else if(flag == 2) printf("NONE\n");
else intersection(line1.a,line1.b-line1.a,line2.a,line2.b-line2.a);
}
printf("END OF OUTPUT\n");
return 0;
}