POJ1269 Intersecting Lines
2017年8月7日链接:http://poj.org/problem?id=1269
给你两条直线,判断相交不相交.相交求交点.
都用叉积来解决就好了.
先用叉积来判断两条直线是否平行,平行的话要么是重合,要么是不重合,再取任意一点用叉积判断这点是否在另一条直线上,在的话就是重合了.
不平行的话,就会有交点,假设交点为P_0(x_0,y_0).
由叉积原理,有
\\begin{cases}
(P_1-P_0)\\times(P_2-P_0) = 0\\\\
(P_3-P_0)\\times(P_2-P_0) = 0\\\\
\\end{cases}
展开得
\\begin{cases}
(y_1-y_2)x_0+(x_2-x_1)y_0+x_1y_2-x_2y_1=0\\\\
(y_3-y_4)x_0+(x_4-x_3)y_0+x_3y_4-x_4y_3=0\\\\
\\end{cases}
解出 x_0,y_0即可
#include <cstdio>
#include <cmath>
#include <algorithm>
using namespace std;
const double EPS = 1e-9;
const int N = 10;
int sgn(double x)
{
if (fabs(x) < EPS)
return 0;
return x < 0 ? -1 : 1;
}
struct Point {
double x, y;
Point(){}
Point(double x, double y): x(x), y(y) {}
void read() {
scanf("%lf %lf", &x, &y);
}
Point operator + (const Point &a) const {
return Point(x + a.x, y + a.y);
}
Point operator - (const Point &a) const {
return Point(x - a.x, y - a.y);
}
} P[N];
double cross(Point a, Point b)
{
return a.x * b.y - a.y * b.x;
}
struct Line {
Point s, e;
Line(){}
Line(Point a, Point b) {
s = a, e = b;
}
pair<Point, int> operator & (const Line &b) const {
Point res = s;
if (sgn(cross(s - e, b.s - b.e)) == 0) {
return sgn(cross(b.s - s, b.e - s)) ? make_pair(res, 1) : make_pair(res, 0);
}
double t = 1.0 * cross(s - b.s, b.s - b.e) / cross(s - e, b.s - b.e);
res.x += (e.x - s.x) * t;
res.y += (e.y - s.y) * t;
return make_pair(res, 2);
}
} line[2];
int main()
{
printf("INTERSECTING LINES OUTPUT\n");
int n;
scanf("%d", &n);
while (n--) {
for (int i = 1; i <= 4; i++) {
P[i].read();
}
line[0] = Line(P[1], P[2]);
line[1] = Line(P[3], P[4]);
pair<Point, int> ans = line[0] & line[1];
if (ans.second == 0) {
printf("LINE\n");
} else if (ans.second == 1) {
printf("NONE\n");
} else {
printf("POINT %.2lf %.2lf\n", ans.first.x, ans.first.y);
}
}
printf("END OF OUTPUT\n");
return 0;
}