Cod sursa(job #3372829)

Utilizator paul_gabryelPaul Buda paul_gabryel Data 5 noiembrie 2026 08:56:07
Problema Cele mai apropiate puncte din plan Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.55 kb
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <fstream>
#include <vector>
using namespace std;

using i64 = long long;
using u64 = unsigned long long;
struct Point { i64 x, y; };

static vector<Point> points;
static vector<Point> merge_buffer;
static vector<Point> strip;

static inline u64 squared_distance(const Point &a, const Point &b) {
    u64 delta_x = (u64)llabs(a.x - b.x);
    u64 delta_y = (u64)llabs(a.y - b.y);
    return delta_x * delta_x + delta_y * delta_y;
}

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

static u64 closest_pair(int begin, int end) {
    u64 best = ~0ULL;

    if (end - begin <= 3) {
        for (int first = begin; first < end; first++)
            for (int second = first + 1; second < end; second++)
                best = min(best, squared_distance(points[first], points[second]));
        sort(points.begin() + begin, points.begin() + end, by_y);
        return best;
    }

    int middle = (begin + end) / 2;
    i64 dividing_x = points[middle].x;
    best = min(closest_pair(begin, middle), closest_pair(middle, end));

    merge(points.begin() + begin, points.begin() + middle,
          points.begin() + middle, points.begin() + end,
          merge_buffer.begin() + begin, by_y);
    copy(merge_buffer.begin() + begin, merge_buffer.begin() + end, points.begin() + begin);

    int strip_size = 0;
    for (int index = begin; index < end; index++) {
        u64 distance_to_line = (u64)llabs(points[index].x - dividing_x);
        if (distance_to_line * distance_to_line < best) strip[strip_size++] = points[index];
    }

    // each point needs to be checked against at most the next 7 in the strip
    for (int first = 0; first < strip_size; first++)
        for (int second = first + 1; second < strip_size && second <= first + 7; second++) {
            u64 vertical_gap = (u64)(strip[second].y - strip[first].y);
            if (vertical_gap * vertical_gap >= best) break;
            best = min(best, squared_distance(strip[first], strip[second]));
        }
    return best;
}

int main() {
    ifstream input("cmap.in");
    int point_count;
    input >> point_count;
    points.resize(point_count);
    merge_buffer.resize(point_count);
    strip.resize(point_count);
    for (auto &point : points) input >> point.x >> point.y;

    sort(points.begin(), points.end(), [](const Point &a, const Point &b) {
        return a.x < b.x || (a.x == b.x && a.y < b.y);
    });

    FILE *output = fopen("cmap.out", "w");
    fprintf(output, "%.6f\n", sqrt((double)closest_pair(0, point_count)));
    fclose(output);
}