題目
給N(0<N<=1e4)個點,座標範圍[0,4e4],
求N個點之間的最近點對的距離,
如果該距離大於1e4,輸出INFINITY,否則輸出距離
思路來源
《挑戰程序設計競賽》第二版
題解
先按x軸排增序,分治,考慮跨軸的貢獻,
設當前左右兩邊已經遞歸出最小距離爲d,
枚舉中點的x值爲當前中軸時,只考慮距中軸距離d以內的點,視爲合法點
對於[l,r)區間,歸併按y增序排序,
枚舉每個合法點,在vector裏向回檢查距離當前合法點y軸距離在d以內的點,
並不斷將合法點加入vector,能更新d就更新d
代碼
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=1e4+10;
const double INF=2e4,mx=1e4,eps=1e-6;
int n;
struct node
{
double x,y;
}e[N],f[N];
bool cmp1(node a,node b)
{
return a.x<b.x;
}
bool operator<(node a,node b)
{
return a.y<b.y;
}
double cal(node a,node b)
{
return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));
}
void merge(node *e,int l,int r)//歸併
{
if(l+1>=r)return;
int mid=(l+r+1)>>1,a=l,b=mid,c=0;//[l,mid)[mid,r)
for(;a<mid||b<r;)
{
if(a<mid&&(b==r||e[a]<e[b]))f[c++]=e[a++];
else f[c++]=e[b++];
}
for(int i=0;i<c;++i)
e[l+i]=f[i];
}
double cdq(int l,int r)
{
if(l+1>=r)return INF;
int mid=(l+r+1)>>1;
double x=e[mid].x;
double d=min(cdq(l,mid),cdq(mid,r));
merge(e,l,r);//在本區間內按y增序歸併
vector<node>b;
for(int i=l;i<r;++i)
{
if(fabs(e[i].x-x)>=d)continue;//距軸超過d
for(int j=0;j<b.size();++j)//按y增序排 先往回找近的
{
double dx=e[i].x-b[b.size()-1-j].x;
double dy=e[i].y-b[b.size()-1-j].y;
if(dy>=d)break;//向回找 y距離超過d即break
d=min(d,sqrt(dx*dx+dy*dy));
}
b.push_back(e[i]);
}
return d;
}
int main()
{
while(~scanf("%d",&n)&&n)
{
for(int i=0;i<n;++i)
scanf("%lf%lf",&e[i].x,&e[i].y);
sort(e,e+n,cmp1);
double ans=cdq(0,n);
if(ans>mx+eps)puts("INFINITY");
else printf("%.4lf\n",ans);
}
return 0;
}