Cod sursa(job #2889135)

Utilizator UgaBuga2Anca Alexandru UgaBuga2 Data 12 aprilie 2022 12:20:07
Problema Cele mai apropiate puncte din plan Scor 0
Compilator c-64 Status done
Runda Arhiva educationala Marime 1.86 kb
#include <stdio.h>
#include <float.h>
#include <stdlib.h>
#include <math.h>

typedef struct
{
    int x, y;
} Punct;

int cmpX(const void* a, const void* b)
{
    Punct *p1 = (Punct *)a, *p2 = (Punct *)b;
    return (p1->x - p2->x);
}

int cmpY(const void* a, const void* b)
{
    Punct *p1 = (Punct *)a, *p2 = (Punct *)b;
    return (p1->y - p2->y);
}

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

float min(float x, float y)
{
    if(x<y)
        return x;
    return y;
}

float BF(Punct P[], int n)
{
    float min = dist(P[0],P[1]);
    for (int i = 1; i < n; ++i)
        for (int j = i+1; j < n; ++j)
            if (dist(P[i], P[j]) < min)
                min = dist(P[i], P[j]);
    return min;
}

float MinY(Punct V[], int n, float d)
{
    float min = d;
    qsort(V, n, sizeof(Punct), cmpY);
    for (int i = 0; i < n; ++i)
        for (int j = i+1; j < n && (V[j].y - V[i].y) < min; ++j)
            if (dist(V[i],V[j]) < min)
                min = dist(V[i], V[j]);
    return min;
}

float MinX(Punct P[], int n)
{
    if (n <= 3)
        return BF(P, n);
    int mij = n/2;
    Punct Pmij = P[mij];
    float ds = MinX(P, mij);
    float dd = MinX(P + mij, n-mij);
    float d = min(ds, dd);
    Punct V[n];
    int j = 0;
    for (int i = 0; i < n; i++)
        if (abs(P[i].x - Pmij.x) < d)
            V[j] = P[i], j++;
    return min(d, MinY(V, j, d) );
}

int main()
{
    FILE *f=fopen("cmap.in","r");
    int n;
    fscanf(f,"%d",&n);
    Punct *P=malloc(n*sizeof(Punct));
    for(int i=0; i<n; i++)
        fscanf(f,"%d %d",&P[i].x,&P[i].y);
    fclose(f);
    FILE *g=fopen("cmap.out","w");
    qsort(P, n, sizeof(Punct), cmpX);
    fprintf(g,"Cea mai mica distanta este : %f ", MinX(P, n));
    fclose(g);
    return 0;
}