参考资料:
- https://www.cnblogs.com/zyxStar/p/4591897.html
问题引入
给出一个平面内所有点的坐标, 求出这些点中最近的两个点的距离
分治算法
- 将所有点按照横坐标的顺序从小到大排序
- 根据中间点的坐标将整个平面划分成两部分
此时, 原问题转化成了3个子问题:
- 在左半平面求最近点对
- 在右半平面求最近点对
- 对分别在左半平面和右半平面的两个点求最近点对
对于子问题1, 2而言, 问题的规模相较于原问题显然减少了一半. 有两种让递归终止的条件:
- 某个半平面没有点, 此时保持原答案
ans
不变 - 某半个平面内只有两个点
a
和b
, 此时将答案更新为原答案ans
和a
与b
之间距离的较小者.
对于子问题3而言, 我们可以采用如下方法缩小问题规模:
- 选取所有与中间点的横坐标之差不超过
ans
的点, 将这些点的序号保存在一个临时的数组里. - 将这些点根据纵坐标的顺序从小到大进行排序, 然后暴力求解这些点的距离, 并适时更新答案
代码实现
#include<iostream>
#include<algorithm>
#include<cmath>
#include<stdio.h>
using namespace std;
const double INF =1e15; //设定一个足够大的初始值
class point {
public:
double x, y;
public:
bool operator <(const point b) {
if (x==b.x) return y < b.y;
else return x < b.x;
}
};
point arr[100005];
int temp[100005];
double ans = INF;
int n;
bool cmp(int a, int b) {
return arr[a].y < arr[b].y;
}
double dis(const point& a, const point& b) {
return sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y));
}
void closest(int L, int R) {
if (L >= R) return;
else if (R - L == 1) {
ans = min(ans, dis(arr[L], arr[R]));
return;
}
int mid = (L + R) >> 1;
closest(L, mid - 1);
closest(mid + 1, R);
int cnt = 0;
for (int i = L; i <= R; i++) {
if (fabs(arr[i].x - arr[mid].x) <= ans) temp[cnt++] = i;
}
sort(temp, temp + cnt, cmp);
for (int i = 0; i < cnt; i++) {
for (int j = i + 1; j < cnt; j++) {
if (arr[temp[j]].y - arr[temp[i]].y > ans) break;
ans = min(ans, dis(arr[temp[i]], arr[temp[j]]));
}
}
}
int main() {
cin >> n;
for (int i = 0; i < n; i++) cin >> arr[i].x >> arr[i].y;
sort(arr, arr + n);
closest(0, n - 1);
printf("%.4lf", ans);
return 0;
}