问题:
给定平面上N个点的坐标,找出距离最近的两个点。
解法:
我们先对N个点的x坐标进行排序,排序我们使用最坏复杂度O(n*logn)的快速排序方法,在排序的过程中minDifferent会递归计算出左右两边的最小距离,再用其中的较小值minum得到以中位数点附近的带状区域[p[median+1].x-median, p[median].x+median],对带状区域的点按照y坐标排序,对带状区域的每个点只需计算最多7个点,就能得到所有可能小于minum的点对。
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
// 顶点信息
struct Point
{
double m_x, m_y;
Point():m_x(0.0),m_y(0.0) {}
Point(double x, double y):m_x(x),m_y(y){}
bool operator==(const Point& p) const
{return m_x==p.m_x && m_y==p.m_y;}
};
ostream& operator<<(ostream& os, const Point& p)
{
return os << "(" << p.m_x << "," << p.m_y << ")";
}
// 插入排序
template<class T, class Pr>
void insert_sort(vector<T> &vec, int l, int r, Pr pred)
{
int i, j;
for (i=l+1; i<=r; i++)
{
T tmp = vec[i];
for (j=i-1; j>=l && pred(tmp,vec[j]); j--)
vec[j+1]=vec[j];
vec[j+1] = tmp;
}
}
// 找到key所在的位置
template<class T>
int get_position(vector<T> &vec, int l, int r, T key)
{
for (int i=l; i<=r; i++)
if (key == vec[i])
return i;
return -1;