跳到正文

题解

题解:AT_abc286_h [ABC286Ex] Don't Swim

Charged_Charge约 4 分钟
原文
文章信息与版本

文章信息

收录
2026年3月25日
更新
2026年3月25日
篇幅
约 4 分钟

版本

  1. v1当前

前言:

首次切计算几何紫题,遂发题解祭之。

思路:

假设有这样的一种局面: 先不考虑两点在多边形同一侧的情况,ss 和 tt 相遇走的最短路径一定是下图所描述的两种: 注意到这两种路径就是对多边形上所有点和 ss、tt 两点求凸包后 ss 与 tt 要相遇在凸包上行走的两种方式。求出凸包后,如果凸包的组成点的集合中不完全包含 ss、tt 两点,则说明两点在多边形同一侧,直接输出两点距离。否则分别求出两种路径的长度取较小值输出即可。

AC 代码:

C++
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N = 1e5 + 10;
int n, idx, tot = -1;
struct node {
	int x, y;
} a[N], s, t, st[N], pr[N];

bool cmp(node l, node r) {
	if (l.x != r.x) {
		return l.x < r.x;
	}

	return l.y < r.y;
}

double cross(node a, node b) {
	return a.x * b.y - a.y * b.x;
}

double side(node p, node p1, node a) {
	node x = {p1.x - p.x, p1.y - p.y};
	node y = {a.x - p.x, a.y - p.y};
	return cross(x, y);
}

double d(node a, node b) {
	return sqrt((b.x - a.x) * (b.x - a.x) + (b.y - a.y) * (b.y - a.y));
}

signed main() {
	cin >> n;

	for (int i = 1; i <= n; i++) {
		cin >> a[i].x >> a[i].y;
	}

	cin >> s.x >> s.y >> t.x >> t.y;
	a[++n] = s;
	a[++n] = t;

	sort(a + 1, a + 1 + n, cmp);
	st[1] = a[1], st[2] = a[2];
	idx = 2;

	for (int i = 3; i <= n; i++) {
		while (idx > 1 && side(st[idx - 1], st[idx], a[i]) <= 0) {
			idx--;
		}

		st[++idx] = a[i];
	}

	for (int i = 1; i < idx; i++) {
		pr[++tot] = st[i];
	}

	idx = 0;
	st[++idx] = a[n];
	st[++idx] = a[n - 1];

	for (int i = n - 2; i >= 1; i--) {
		while (idx > 1 && side(st[idx - 1], st[idx], a[i]) <= 0) {
			idx--;
		}

		st[++idx] = a[i];
	}

	for (int i = 1; i <= idx; i++) {
		pr[++tot] = st[i];
	}

	int sum = 0;
	int sr = 0, ed = 0;

	for (int i = 0; i < tot; i++) {
		if ((pr[i].x == s.x && pr[i].y == s.y) || (pr[i].x == t.x && pr[i].y == t.y)) {
			sum++;
		}

		if (pr[i].x == s.x && pr[i].y == s.y) {
			sr = i;
		}

		if (pr[i].x == t.x && pr[i].y == t.y) {
			ed = i;
		}
	}

	if (sum < 2) {
		cout << fixed << setprecision(8) << d(s, t);
		return 0;
	}

	double a1 = 0, a2 = 0;

	for (int i = sr; i != ed; i = (i + 1) % tot) {
		a1 += d(pr[i], pr[(i + 1) % tot]);
	}

	for (int i = ed; i != sr; i = (i + 1) % tot) {
		a2 += d(pr[i], pr[(i + 1) % tot]);
	}

	cout << fixed << setprecision(8) << min(a1, a2);
	return 0;
}
原文