洛谷P1429 平面最近点对(加强版)题解

题目大意:求平面最近点对。

解题思路:分治经典问题。

示例程序:

#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 5;

struct Node {
    double x, y;
} a[maxn], b[maxn];

bool cmp_x(Node a, Node b) {
    return a.x < b.x;
}

bool cmp_y(Node a, Node b) {
    return a.y < b.y;
}

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

int n;

double solve(int l, int r) {
    if (l >= r) return 2e9;
    int mid = (l + r) / 2;
    double d = min(solve(l, mid), solve(mid+1, r));
    int p = 0;
    for (int i = l; i <= r; i++) if (abs(a[i].x - a[mid].x) < d) b[p++] = a[i];
    sort(b, b+p, cmp_y);
    for (int i = 0; i < p; i++)
        for (int j = i+1; j < p && b[j].y - b[i].y < d; j++)
            d = min(d, dis(b[i], b[j]));
    return d;
}

int main() {
    scanf("%d", &n);
    for (int i = 1; i <= n; i++) scanf("%lf%lf", &a[i].x, &a[i].y);
    sort(a+1, a+n+1, cmp_x);
    printf("%.4lf\n", solve(1, n));
    return 0;
}
posted @ 2023-03-28 22:33  quanjun  阅读(26)  评论(0编辑  收藏  举报