## 1097: 最近点对
题目描述:
要求用分治算法(O(nlogn)复杂度)实现寻找n个点中最邻近点对,输出最近距离的平方。
其中0<=x<10000,0<=y<10000,(x,y取整数或者小数点后一位)
点数1<n<=30000.
输入:
第一行表示点的数目n;
接下来的n行中,每一行依次表示点的x坐标,y坐标。
输出:
输出n个点中最邻近点对距离的平方(小数点后两位)
代码:
#include<iostream>
#include<algorithm>
#include<cmath>
#include<vector>
using namespace std;
class Node
{
public:
float x;
float y;
public:
Node() {}
Node(float x, float y)
{
this->x = x;
this->y = y;
}
};
Node *X;
Node *Y;
int n;
bool comparex(const Node &a, const Node &b)
{
return a.x < b.x;
}
bool comparey(const Node &a, const Node &b)
{
return a.y < b.y;
}
float dis(Node a, Node b)
{
return sqrt((a.x - b.x)*(a.x - b.x) + (a.y - b.y)*(a.y - b.y));
}
float find_min_dis(int start, int end)
{
int len = end - start + 1;
if (len == 1)
{
return INFINITY;
}
else if (len == 2)
{
return dis(X[start], X[end]);
}
else
{
vector<Node> S;
float min1 = find_min_dis(start, start + len / 2 - 1);
float min2 = find_min_dis(start + len / 2, end);
float delt = min1 > min2 ? min2 : min1;
float min3 = INFINITY;
float L = X[len / 2].x;
for (int i = 0; i < n; i++)
{
if (abs(Y[i].x - L) < delt)S.push_back(Y[i]);
}
for (int i = 0; i < S.size(); i++)
{
for (int j = 1; S[j].y-S[i].y<delt && i + j < S.size(); j++)
{
min3 = min3 > dis(S[i], S[i + j]) ? dis(S[i], S[i + j]) : min3;
}
}
float min = min3 > delt ? delt : min3;
return min;
}
}
int main()
{
cin >> n;
X = new Node[n];
Y = new Node[n];
for (int i = 0; i < n; i++)
{
float p, q;
cin >> p >> q;
Node newNode(p, q);
X[i] = newNode;
Y[i] = newNode;
}
sort(X, X + n, comparex);
sort(Y, Y + n, comparey);
float min = find_min_dis(0, n - 1);
cout << min*min;
}