计算几何——[poj_1269]Intersecting Lines

Intersecting Lines

题目意思比较清楚,给你四个点,组成两条直线,判断直线是否有交点,有交点就求出来,否则就判断是不相交还是重合。

注意点: 判断直线相交的时候要判断斜率不存在的情况。

会求斜率就行了。

#include<algorithm>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<iostream>
#include<queue>
#include<map>
#include<vector>
#include<set>
#include<string>
using namespace std;
typedef long long ll;
const int N = 1e5 + 10;
const int INF = 0x3f3f3f3f;
#define endl '\n'
#define pb(a) push_back(a)
#define al(x) x.begin(), x.end()
#define sz(x) int(x.size())
#define IOS ios::sync_with_stdio(0);

struct Point {
	int x, y;
	Point(int x = 0, int y = 0): x(x), y(y) {}
};

Point operator - (const Point&A, const Point&B) {
	return Point(A.x - B.x, A.y - B.y);
}

struct Line { //直线定义
	Point v, p;
	Line() {}
	Line(Point v, Point p): v(v), p(p) {}
} line[2];
int n;

int Cross(Point A, Point B) {
	return A.x * B.y - A.y * B.x;
}

int ok(Point A, Point B, Point C, Point D) {
// return:  -1:相交   1:不相交   0:重合
	// 其中一条直线垂直x轴
	if ((A.x == B.x && C.x != D.x) || (A.x != B.x && C.x == D.x)) {
		return -1;
	}
	// 两条都垂直x轴
	if (A.x == B.x && C.x == D.x) {
		return A.x == C.x ? 0 : 1;
	}
	// 计算斜率
	double k1 = 1.0 * (B.y - A.y) / (B.x - A.x);
	double k2 = 1.0 * (D.y - C.y) / (D.x - C.x);
	if (k1 != k2) return -1;
	if (A.y - k1 * A.x == C.y - k2 * C.x) return 0;
	return 1;
}

void solve(Line A, Line B) {
	Point a = A.p, b = A.v, c = B.p, d = B.v;
	int f = ok(a, b, c, d);
	if (f == 1) puts("NONE");
	else if (!f) puts("LINE");
	else {
		// 处理垂直的情况
		if (a.x == b.x) {
			double b2 = 1.0 * Cross(d, c) / (d.x - c.x);
			double k2 = 1.0 * (d.y - c.y) / (d.x - c.x);
			double y = 1.0 * k2 * a.x + b2;
			printf("POINT %.2f %.2f\n", 1.0 * a.x, y);
		} else if (c.x == d.x) {
			double b1 = 1.0 * Cross(b, a) / (b.x - a.x);
			double k1 = 1.0 * (b.y - a.y) / (b.x - a.x);
			double y = 1.0 * k1 * c.x + b1;
			printf("POINT %.2f %.2f\n", 1.0 * c.x, y);
		} else {
			double b1 = 1.0 * Cross(b, a) / (b.x - a.x);
			double b2 = 1.0 * Cross(d, c) / (d.x - c.x);
			double k1 = 1.0 * (b.y - a.y) / (b.x - a.x);
			double k2 = 1.0 * (d.y - c.y) / (d.x - c.x);
			double x = -1.0 * (b2 - b1) / (k2 - k1);
			double y = 1.0 * k1 * x + b1;
			printf("POINT %.2f %.2f\n", x, y);
		}
	}
}

int main() {
	Point a, b, c, d;
	scanf("%d", &n);
	puts("INTERSECTING LINES OUTPUT");
	for (int i = 0; i < n; ++i) {
		scanf("%d%d%d%d%d%d%d%d", &a.x, &a.y, &b.x, &b.y, &c.x, &c.y, &d.x, &d.y);
		line[0] = Line(a, b);
		line[1] = Line(c, d);
		solve(line[0], line[1]);
	}
	puts("END OF OUTPUT");
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值