Introduction to algorithms in the computational geometry section describes the method for finding the nearest vertex pair: using typical partitioning Algorithms
(1) decomposition: after sorting all vertices by X coordinates, they are roughly divided into two sets of equal sizes, L and R.
(2) solution: Find the minimum and specific values in the L and R sets respectively, and take the smaller values of the two as the current minimum ans.
(3) Merge: For points in two sets, each time a vertex is taken out, the distance between two points is calculated, and the value of ANS is updated by comparing a smaller value with ans each time, you can also perform optimization. There are three specific optimization steps. For details, see Introduction to algorithms.
The algorithm runs at O (n log n). The specific code is as follows:
#include <cstdio>#include <algorithm>#include <cmath>using namespace std;int const MAX_N = 100005;struct Point{double x, y;};Point p[MAX_N];int yy[MAX_N];bool cmpx(Point const& pa, Point const& pb){return pa.x < pb.x;}bool cmpy(int const& a, int const& b){return p[a].y < p[b].y;}inline double dis(Point const& pa, Point const& pb){return sqrt((pa.x - pb.x) * (pa.x - pb.x) + (pa.y - pb.y) * (pa.y - pb.y));}inline double min(double const& a, double const& b){return a < b ? a : b;}double closeset(int low, int high){if(low + 1 == high){return dis(p[low], p[high]);}if(low + 2 == high){return min(dis(p[low], p[high]), min(dis(p[low], p[low + 1]), dis(p[low + 1], p[high])));}int mid = (low + high) >> 1;double ans = min(closeset(low, mid), closeset(mid + 1, high));int cnt = 0;for(int i = low; i <= high; i++){if(p[i].x > p[mid].x - ans && p[i].x < p[mid].x + ans){yy[cnt++] = i;}}sort(yy, yy + cnt, cmpy);for(int i = 0; i < cnt; i++){int k = (i + 7) > cnt ? cnt : (i + 7);for(int j = i + 1; j < k; j++){if(p[yy[j]].y - p[yy[j]].y >= ans)break;ans = min(ans, dis(p[yy[j]], p[yy[i]]));}}return ans;}int main(){//freopen("min.txt", "r", stdin);int n, i;while(scanf("%d", &n) != EOF){if(!n)break;for(i = 0; i < n; i++){scanf("%lf %lf", &p[i].x, &p[i].y);}sort(p, p + n, cmpx);double ans = closeset(0, n - 1);printf("%.2lf\n", ans);}return 0;}
Introduction to algorithms-nearest vertex pair