洛谷P1257

P1257 平面上的最接近点对

这题的数据其实直接暴力枚举就可以了,但是书里是放在分治章节的。
题目越来越难了,我现在感觉真的很吃力😟

点击查看暴力枚举代码
#include<bits/stdc++.h>
using namespace std;

const int N = 10005;
struct Point {
    double x, y;
} p[N];

int main() {
    int n; cin >> n;
    for(int i = 0; i < n; i++) {
        cin >> p[i].x >> p[i].y;
    }

    double min_d = 4e18;
    for(int i = 0; i < n; i++) {
        for(int j = i + 1; j < n; j++){
            double dx = p[i].x - p[j].x;
            double dy = p[i].y - p[j].y;
            double dist = dx * dx + dy * dy;
            min_d = min(dist, min_d);
        }
    }
    cout << fixed << setprecision(4) << sqrt(min_d) <<'\n';
    return 0;
}
点击查看分治法代码(chatGPT)
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#include <limits>

using namespace std;

struct Point {
    double x, y;
};

bool compareX(const Point &a, const Point &b) {
    return a.x < b.x;
}

bool compareY(const Point &a, const Point &b) {
    return a.y < b.y;
}

double distance(const Point &a, const Point &b) {
    double dx = a.x - b.x;
    double dy = a.y - b.y;
    return sqrt(dx * dx + dy * dy);
}

double closestPairUtil(vector<Point> &Px, vector<Point> &Py) {
    int n = Px.size();
    if (n <= 3) {
        double minDist = numeric_limits<double>::max();
        for (int i = 0; i < n; ++i)
            for (int j = i + 1; j < n; ++j)
                minDist = min(minDist, distance(Px[i], Px[j]));
        return minDist;
    }

    int mid = n / 2;
    Point midPoint = Px[mid];

    vector<Point> Pyl, Pyr;
    for (const auto &point : Py) {
        if (point.x <= midPoint.x)
            Pyl.push_back(point);
        else
            Pyr.push_back(point);
    }

    vector<Point> Pxl(Px.begin(), Px.begin() + mid);
    vector<Point> Pxr(Px.begin() + mid, Px.end());

    double dl = closestPairUtil(Pxl, Pyl);
    double dr = closestPairUtil(Pxr, Pyr);
    double d = min(dl, dr);

    vector<Point> strip;
    for (const auto &point : Py)
        if (abs(point.x - midPoint.x) < d)
            strip.push_back(point);

    double minStripDist = d;
    int stripSize = strip.size();
    for (int i = 0; i < stripSize; ++i)
        for (int j = i + 1; j < stripSize && (strip[j].y - strip[i].y) < minStripDist; ++j)
            minStripDist = min(minStripDist, distance(strip[i], strip[j]));

    return minStripDist;
}

double closestPair(vector<Point> &points) {
    vector<Point> Px = points;
    vector<Point> Py = points;
    sort(Px.begin(), Px.end(), compareX);
    sort(Py.begin(), Py.end(), compareY);
    return closestPairUtil(Px, Py);
}

int main() {
    int n;
    cin >> n;
    vector<Point> points(n);
    for (auto &point : points)
        cin >> point.x >> point.y;

    double result = closestPair(points);
    printf("%.4f\n", result);
    return 0;
}
posted @ 2025-05-23 19:06  Chuan81  阅读(26)  评论(0)    收藏  举报