P4423 题解

· · 题解

我们充分发扬人类智慧:

我们将所有点同时随机平移,然后对所有点进行极角排序。

根据数学直觉,在随机平移并排序后,能成为答案的点对一定不会离得太远。

所以我们只取每个点向后 28 个点进行计算。

这样速度快的飞起,在 n \le 2 \times 10^5 时都能做到 500 毫秒。

AC 代码

#include <bits/stdc++.h>

#define double long double

#define rep(i, a, b) for(int i = (a), i##end = (b); i <= i##end; i++)
#define _rep(i, a, b) for(int i = (a), i##end = (b); i >= i##end; i--)
#define ec first
#define fb second
#define dl make_pair
#define dk(...) make_tuple(__VA_ARGS__)

using namespace std;

typedef long long ll;
typedef pair <int, int> pii;

int read() {
    int x = 0, f = 1; char c = getchar();
    while (!isdigit(c)) {
        if (c == '-') f = -1;
        c = getchar();
    }
    while (isdigit(c)) {
        x = (x << 3) + (x << 1) + (c ^ 48);
        c = getchar();
    }
    return x * f;
}

template <typename _Tp>
void print(_Tp x) {
    if (x < 0) x = (~x + 1), putchar('-');
    if (x > 9) print(x / 10);
    putchar(x % 10 + '0');
}

double ans = 1e15;

double dis(pii a, pii b) {
    return sqrt(1ll * (a.ec - b.ec) * (a.ec - b.ec) + 1ll * (a.fb - b.fb) * (a.fb - b.fb));
}

mt19937 rnd(chrono::steady_clock::now().time_since_epoch().count());

const int MAXN = 1e6 + 5;
int n;
pii pt[MAXN];

signed main() {
#ifndef LOCAL
#ifndef ONLINE_JUDGE
    freopen("triangle.in", "r", stdin);
    freopen("triangle.out", "w", stdout);
#endif
#endif
    const int addr = rnd();
    n = read();
    rep (i, 1, n) pt[i].ec = read() + addr, pt[i].fb = read() + addr;
    sort(pt + 1, pt + n + 1, [](pii a, pii b) { return atan2(a.fb, a.ec) < atan2(b.fb, b.ec); });
    rep (i, 1, n) {
        rep (j, i + 1, min(n, i + 28)) {
            rep (k, j + 1, min(n, i + 28)) {
                if (i == j || j == k || i == k) continue;
                double tans = dis(pt[i], pt[j]) + dis(pt[j], pt[k]) + dis(pt[k], pt[i]);
                if (tans < ans) {
                    ans = tans;
                }
            }
        }
    }
    printf("%.6Lf", ans);
    return 0;
}