题解:AT_abc286_h [ABC286Ex] Don't Swim
Charged_Charge · · 题解
前言:
首次切计算几何紫题,遂发题解祭之。
思路:
假设有这样的一种局面:
先不考虑两点在多边形同一侧的情况,
AC 代码:
#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;
}