http://acm.hdu.edu.cn/showproblem.php?pid=1007
题意:求平面最近点对距离的一半,点数
n
<
=
100000
n<=100000
n<=100000。
平面最近点对暴力 O ( n 2 ) O(n^2) O(n2),用分治的方法可以做到 O ( n l o g n ) O(nlogn) O(nlogn),具体就是先按横坐标为第一关键字排序,然后关于横坐标进行分治,递归得到 p [ m i d ] p[mid] p[mid]左右两边的最近点对距离,合并是关键步骤,得到左边最近距离 d 1 d1 d1和右边最近距离 d 2 d2 d2,然后得到 d = m i n ( d 1 , d 2 ) d=min(d1,d2) d=min(d1,d2),但是现在还需考虑跨越两边的情况,而这种情况只可能出现在 p [ m i d ] p[mid] p[mid]左右 d d d范围以内的点中,取出这些点按纵坐标进行排序然后将 d d d与这些点中可能的距离进行比较得到合理的最近距离。
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <cmath>
using namespace std;
const int MAXN=100010;
const double eps=1e-6;
const double INF=1e20;
struct Point
{
double x,y;
};
double dist(Point a,Point b)
{
return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));
}
Point p[MAXN];
Point tmpt[MAXN];
bool cmpxy(Point a,Point b)
{
if(a.x!=b.x) return a.x<b.x;
else return a.y<b.y;
}
bool cmpy(Point a,Point b)
{
return a.y<b.y;
}
double Closest_Pair(int left,int right)//分治,返回最近点对的距离
{
double d=INF;
if(left==right) return d;
if(left+1==right) return dist(p[left],p[right]);
int mid=(left+right)/2;
//分别得到左右两边的最短距离d1和d2
double d1=Closest_Pair(left,mid);
double d2=Closest_Pair(mid,right);
d=min(d1,d2);
int k=0;
//合并的时候只需再考虑跨越左右的情况
//且只需考虑p[mid]左右d以内的点
for(int i=left;i<=right;i++)
{
if(fabs(p[mid].x-p[i].x)<=d)
tmpt[k++]=p[i];
}
sort(tmpt,tmpt+k,cmpy);//对这些点按纵坐标排序
for(int i=0;i<k;i++)
{
for(int j=i+1;j<k&&tmpt[j].y-tmpt[i].y<d;j++)
{
d=min(d,dist(tmpt[i],tmpt[j]));
}
}
return d;
}
int main()
{
int n;
while(1)
{
scanf("%d",&n);
if(n==0) break;
for(int i=0;i<n;i++)
scanf("%lf%lf",&p[i].x,&p[i].y);
sort(p,p+n,cmpxy);//按横坐标为第一关键字排序
printf("%.2lf\n",Closest_Pair(0,n-1)/2);
}
return 0;
}
本文介绍了一种使用分治策略解决平面最近点对问题的高效算法,通过按横坐标排序和递归分解,最终实现O(nlogn)的时间复杂度。文章详细解释了算法流程,包括如何处理跨越中间线的点对情况。
540

被折叠的 条评论
为什么被折叠?



