// ClosestTwoPoints.cpp : Defines the entry point for the console application.
//
#include <iostream>
#include <vector>
#include <algorithm>
#include <fstream>
#include <math.h>
using namespace std;
struct Point
{
float x, y;
};
bool increasingX(const Point a, const Point b)
{
return a.x < b.x;
}
bool increasingY(const Point a, const Point b)
{
return a.y < b.y;
}
float minf(const float a, const float b)
{
return (a < b) ? a : b;
}
float distance(const Point a, const Point b)
{
return (sqrt((b.x - a.x)*(b.x - a.x) + (b.y - a.y)*(b.y - a.y)));
}
float closestDistance(int st, int dr, vector<Point> &X, vector<Point> &Y,Point &first,Point &second)
{
if (dr - st < 4)
{
float mind = 10000000000;
int pos1 = -1, pos2 = -1;
for (int i = 0; i < dr; i++)
{
for (int j = i+1; j <= dr; j++)
{
float distaux = distance(X[i], X[j]);
if (distaux < mind)
{
mind = distaux;
pos1 = i;
pos2 = j;
}
}
}
if (pos1 != -1 && pos2 != -2)
{
first = X[pos1];
second = X[pos2];
return mind;
}
else
{
cerr << "Error in closestDistance()\n";
return -1;
}
}
else
{
// Divide
int mij = (st + dr) / 2;
vector<Point> SY; // Ordonate dupa y din stanga planului
vector<Point> DY; // Ordonate dupa y din dreapta planului
// Calculam SY si DY
for (size_t i = 0; i < Y.size(); i++)
{
if (Y[i].x < mij)
SY.push_back(Y[i]);
else
DY.push_back(Y[i]);
}
Point f1, f2, f3, s1, s2, s3;
float d1 = closestDistance(st, mij, X, SY, f1, s1);
float d2 = closestDistance(mij + 1, dr, X, DY, f2, s2);
float delta = minf(d1, d2);
float d3 = 10000000000;
// Ne uitam in banda
vector<Point> LY;
for (size_t i = 0; i < Y.size(); i++)
{
if (abs(Y[i].x - mij) < delta)
LY.push_back(Y[i]);
}
for (size_t i = 0; i < LY.size() - 1; i++)
{
for (size_t j = i + 1; j < LY.size(); j++)
{
float aux = distance(LY[i], LY[j]);
if (aux < d3)
{
f3 = LY[i];
s3 = LY[j];
d3 = aux;
}
else if (aux > delta)
break;
}
}
// Stabilim care e distanta minima si punctele ce o formeaza
if (minf(delta, d3) == delta)
{
if (delta == d1)
{
first = f1;
second = s1;
return d1;
}
else
{
first = f2;
second = s2;
return d2;
}
}
else
{
first = f3;
second = s3;
return d3;
}
}
}
int main()
{
int n;
ifstream fin("date.txt");
fin >> n;
vector<Point> arr_x(n), arr_y(n);
float xx, yy;
for (int i = 0; i < n; i++)
{
fin >> xx >> yy;
arr_x[i].x = arr_y[i].x = xx;
arr_x[i].y = arr_y[i].y = yy;
}
fin.close();
sort(arr_x.begin(), arr_x.end(), increasingX);
sort(arr_y.begin(), arr_y.end(), increasingY);
Point p1, p2;
cout << closestDistance(0,n-1,arr_x,arr_y,p1,p2) << endl;
cout << "(" << p1.x << "," << p1.y << ") , " << "(" << p2.x << "," << p2.y << ")\n";
return 0;
}