链接:hdu1007
- 平面最近点对问题
- 采用分治,复杂度为O(Knlognlogn)
- 先考虑一维的情况(虽然可以O(n)扫一遍)
- 将序列按
#include
#include
#include
#include
#include
#include
#define rep(i,x,y) for(register int i=x;i<=y;++i)
#define repd(i,x,y) for(register int i=x;i>=y;--i)
#define ll long long
using namespace std;
const double dnf=0x3f3f3f3f;
const int N=1e5+7;
double x[N],y[N];
int tmp[N],id[N],cnt,n;
inline double dis(int a,int b){return sqrt((x[a]-x[b])*(x[a]-x[b])+(y[a]-y[b])*(y[a]-y[b]));}
inline int cmpx(int a,int b){return x[a]==x[b]?y[a]inline int cmpy(int a,int b){return y[a]double solve(int l,int r){
if(l==r)return dnf;
if(r==l+1)return dis(id[l],id[r]);
int mid=l+r>>1;
double d1=solve(l,mid);
double d2=solve(mid+1,r);
double d=min(d1,d2);cnt=0;
rep(i,l,r)if(dis(id[i],id[mid])<=d)tmp[++cnt]=id[i];
sort(tmp+1,tmp+cnt+1,cmpy);
rep(i,1,cnt)for(int j=i+1;j<=cnt&&y[tmp[j]]-y[tmp[i]]double tp=dis(tmp[i],tmp[j]);d=min(tp,d);}
return d;
}
int main(){
while(~scanf("%d",&n)&&n){
rep(i,1,n){scanf("%lf%lf",&x[i],&y[i]);id[i]=i;}
sort(id+1,id+n+1,cmpx);
printf("%.2lf\n",solve(1,n)/2);
}
return 0;
}
- 看到某个大佬用奇怪的方式O(
n2 n 2)暴力过了
#include
#include
#include
#include
#include
#include
#define rep(i,x,y) for(register int i=x;i<=y;++i)
#define repd(i,x,y) for(register int i=x;i>=y;--i)
#define ll long long
using namespace std;
const double dnf=0x3f3f3f3f;
const int N=1e5+7;
struct node{
double x,y;
inline void init(){scanf("%lf%lf",&x,&y);}
}a[N],b[N];
int n;
inline int cmpx(const node &x,const node &y){return x.xinline int cmpy(const node &x,const node &y){return x.yinline double dis(node &x,node &y){return sqrt((x.x-y.x)*(x.x-y.x)+(x.y-y.y)*(x.y-y.y));}
int main(){
while(~scanf("%d",&n)&&n){
double d=dnf;
int tot1=0,tot2=100;
rep(i,1,n)a[i].init();
rep(i,1,n)b[i]=a[i];
sort(a+1,a+n+1,cmpx);
sort(b+1,b+n+1,cmpy);
for(int i1=2,i2=2,j1=1,j2=1;i1<=n&&i2<=n;){
repd(k,j1,1){
d=min(d,dis(a[i1],a[k]));
if(a[i1].x-a[k].x>=d||k==1){j1=i1++;break;}
if(tot1>=tot2){tot1+=20;j1=k-1;break;}
tot1++;
}
repd(k,j2,1){
d=min(d,dis(b[i2],b[k]));
if(b[i2].y-b[k].y>=d||k==1){j2=i2++;break;}
if(tot2>=tot1){tot2+=20;j2=k-1;break;}
tot2++;
}
}
printf("%.2lf\n",d/2);
}
return 0;
}