Pagini recente » Cod sursa (job #1622244) | Cod sursa (job #3178766) | Cod sursa (job #2199860) | Cod sursa (job #2356489) | Cod sursa (job #2492230)
// A divide and conquer program in C++
// to find the smallest distance from a
// given set of points.
#include <iostream>
#include <fstream>
#include <algorithm>
#include <cmath>
#include <iomanip>
using namespace std;
ifstream in("cmap.in");
ofstream out("cmap.out");
struct Point
{
int x, y;
};
int compareX(const void* a, const void* b)
{
Point* p1 = (Point*)a, * p2 = (Point*)b;
return (p1->x - p2->x);
}
int compareY(const void* a, const void* b)
{
Point* p1 = (Point*)a, * p2 = (Point*)b;
return (p1->y - p2->y);
}
float dist(Point p1, Point p2)
{
return sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y));
}
float bruteForce(Point P[], int n)
{
float min = FLT_MAX;
for (int i = 0; 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 ClosestMid(Point midarr[], int size, float d)
{
float min = d;
qsort(midarr, size, sizeof(Point), compareY);
for (int i = 0; i < size; ++i)
for (int j = i + 1; j < size && (midarr[j].y - midarr[i].y) < min; ++j)
if (dist(midarr[i], midarr[j]) < min)
min = dist(midarr[i], midarr[j]);
return min;
}
float closestUtil(Point P[], int n)
{
if (n <= 3)
return bruteForce(P, n);
int mid = n / 2;
Point midPoint = P[mid];
float dl = closestUtil(P, mid);
float dr = closestUtil(P + mid, n - mid);
float d = min(dl, dr);
Point midarr[100];
int j = 0;
for (int i = 0; i < n; i++)
if (abs(P[i].x - midPoint.x) < d)
midarr[j] = P[i], j++;
return min(d, ClosestMid(midarr, j, d));
}
float closest(Point P[], int n)
{
qsort(P, n, sizeof(Point), compareX);
return closestUtil(P, n);
}
int main()
{
int n,i;
in >> n;
Point * P = new Point[n];
for (i = 0;i < n;i++)
{
in >> P[i].x >> P[i].y;
}
out <<setprecision(8)<<closest(P, n);
return 0;
}