# 分治法求最接近点对问题

2 篇文章 0 订阅

#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <ctype.h>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>
#define eps 1e-8
#define INF 0x7fffffff
#define PI acos(-1.0)
#define seed 31//131,1313
typedef long long LL;
typedef unsigned long long ULL;
using namespace std;
const int maxn=100005;
struct Point{
double x;
}p[maxn];

int a[maxn];
int cmpx(Point a,Point b){
return a.x<b.x;
}
inline double dis(Point a,Point b){
if(a.x>b.x) return a.x-b.x;
else return b.x-a.x;
}

double closest(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)/2; //求中点即左右子集的分界线
double d=min(closest(low,mid),closest(mid+1,high));
d=min(d,dis(p[mid],p[mid+1])); //最后一步，合并
return d;
}
int main()
{
int n;
while(scanf("%d",&n)!=EOF){
for(int i=0;i<n;i++)
scanf("%lf",&p[i].x);
sort(p,p+n,cmpx);
printf("%.2lf\n",closest(0 , n-1));//最近点对间的距离
}
return 0;
}


“`

• 0
点赞
• 0
评论
• 4
收藏
• 一键三连
• 扫一扫，分享海报

10-28
12-30 3361
11-26 4万+
10-15 7503
08-31 1445
03-12
12-07
07-14 6256
07-13 1944
10-24 1523
03-29 353