【题目链接】
http://poj.org/problem?id=3714
【算法】
分治求平面最近点对
【代码】
#include <algorithm> #include <bitset> #include <cctype> #include <cerrno> #include <clocale> #include <cmath> #include <complex> #include <cstdio> #include <cstdlib> #include <cstring> #include <ctime> #include <deque> #include <exception> #include <fstream> #include <functional> #include <limits> #include <list> #include <map> #include <iomanip> #include <ios> #include <iosfwd> #include <iostream> #include <istream> #include <ostream> #include <queue> #include <set> #include <sstream> #include <stdexcept> #include <streambuf> #include <string> #include <utility> #include <vector> #include <cwchar> #include <cwctype> #include <stack> #include <limits.h> using namespace std; #define MAXN 100010 const double INF = 1e10; int T,i,n; struct info { double x,y; int opt; } a[MAXN<<1]; inline bool cmpx(info a,info b) { return a.x != b.x ? a.x < b.x : a.y < b.y; } inline bool cmpy(info a,info b) { return a.y < b.y; } double dist(info a,info b) { return (a.opt != b.opt) ? sqrt(abs(a.x - b.x) * abs(a.x - b.x) + abs(a.y - b.y) * abs(a.y - b.y)) : INF; } inline double Closest_Pair(int l,int r) { int i,j,mid,len = 0; static info s[MAXN]; double d; if (l == r) return INF; if (l + 1 == r) return dist(a[l],a[r]); mid = (l + r) >> 1; d = min(Closest_Pair(l,mid),Closest_Pair(mid+1,r)); for (i = l; i <= r; i++) { if (abs(a[mid].x - a[i].x) <= d) s[++len] = a[i]; } sort(s+1,s+len+1,cmpy); for (i = 1; i <= len; i++) { for (j = i + 1; j <= len && s[j].y - s[i].y <= d; j++) { d = min(d,dist(s[i],s[j])); } } return d; } int main() { scanf("%d",&T); while (T--) { scanf("%d",&n); for (i = 1; i <= n; i++) { scanf("%lf%lf",&a[i].x,&a[i].y); a[i].opt = 1; } for (i = n + 1; i <= 2 * n; i++) { scanf("%lf%lf",&a[i].x,&a[i].y); a[i].opt = 2; } sort(a+1,a+2*n+1,cmpx); printf("%.3lf\n",Closest_Pair(1,n<<1)); } return 0; }
原文地址:https://www.cnblogs.com/evenbao/p/9240617.html
时间: 2024-11-09 09:54:51