Intersecting Lines POJ - 1269
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/385b07813c4392b5fd57e495be10e859.png)
判断两直线的位置关系
- 判断平行:两直线的向量叉乘为0
- 判断共线:在1的基础上,取一直线上一点与另一直线上一点构成向量后与一直线的向量叉乘为0
- 判断相交并求得交点坐标:不满足1、2的条件下,求出直线上一包含交点的线段与该线段上某一端点到交点的比例系数,在比例系数的基础上求得交点。
AC代码
#include <iostream>
#include <cmath>
using namespace std;
struct P {
double x, y;
P() {}
P(double x, double y) : x(x), y(y) {}
P operator-(const P &b) const {
return P(x - b.x, y - b.y);
}
double operator^(const P &b) const {
return x * b.y - y * b.x;
}
double operator*(const P &b) const {
return x * b.x + y * b.y;
}
};
double const eps = 1e-8;
bool sgn(double x) {
return fabs(x) < eps;
}
struct Line {
P s, e;
Line() {}
Line(P s, P e) : s(s), e(e) {}
pair<int, P> operator&(const Line &b) const {
P ret = s;
if (sgn((s - e) ^ (b.s - b.e))) {
if (sgn((s - b.e) ^ (b.s - b.e))) {
return make_pair(0, ret);
} else return make_pair(1, ret);
} else {
double t = ((s - b.s) ^ (b.s - b.e)) / ((s - e) ^ (b.s - b.e));
ret.x += (e.x - s.x) * t;
ret.y += (e.y - s.y) * t;
return make_pair(2, ret);
}
}
};
int main() {
int T;
cin >> T;
cout << "INTERSECTING LINES OUTPUT\n";
while (T--) {
Line l1, l2;
cin >> l1.s.x >> l1.s.y >> l1.e.x >> l1.e.y;
cin >> l2.s.x >> l2.s.y >> l2.e.x >> l2.e.y;
pair<int, P> ans = l1 & l2;
if (ans.first == 0) cout << "LINE\n";
else if (ans.first == 1) cout << "NONE\n";
else printf("POINT %.2lf %.2lf\n", ans.second.x, ans.second.y);
}
cout << "END OF OUTPUT\n";
return 0;
}