Cod sursa(job #3038315)

Utilizator Danielxp23Daniel Danielxp23 Data 27 martie 2023 11:08:33
Problema Cele mai apropiate puncte din plan Scor 0
Compilator c-64 Status done
Runda Arhiva educationala Marime 1.51 kb
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

typedef struct {
    double x;
    double y;
} coordinate;

int cmp(const void* a, const void* b) {
    coordinate* p1 = (coordinate*)a;
    coordinate* p2 = (coordinate*)b;
    if (p1->y == p2->y) {
        return (p1->x > p2->x) - (p1->x < p2->x);
    } else {
        return (p1->y > p2->y) - (p1->y < p2->y);
    }
}

double dist(coordinate p1, coordinate p2) {
    return sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y));
}

double closest_pair(coordinate* P, int n) {
    if (n <= 1) {
        return INFINITY;
    } else if (n == 2) {
        return dist(P[0], P[1]);
    } else if (n == 3) {
        double d1 = dist(P[0], P[1]);
        double d2 = dist(P[0], P[2]);
        double d3 = dist(P[1], P[2]);
        return fmin(d1, fmin(d2, d3));
    }

    int mid = n / 2;
    double xmid = P[mid].x;

    double dleft = closest_pair(P, mid);
    double dright = closest_pair(P + mid, n - mid);
    double d = fmin(dleft, dright);

    coordinate* strip = (coordinate*)malloc(n * sizeof(coordinate));
    int j = 0;
    for (int i = 0; i < n; i++) {
        if (fabs(P[i].x - xmid) < d) {
            strip[j++] = P[i];
        }
    }
    qsort(strip, j, sizeof(coordinate), cmp);

    for (int i = 0; i < j; i++) {
        for (int k = i + 1; k < j && strip[k].y - strip[i].y < d; k++) {
            double dij = dist(strip[i], strip[k]);
            if (dij < d) {
                d = dij;
            }
        }
    }

    free(strip);
    return d;
}