洛谷p7883
步骤
- 按x为第一关键字,y为第二关键字排序
- 分治:区间中点取为m,左右区间的答案递归实现,专注于解决跨越部分
- h=左,右区间中较小的答案
- 对于区间所有的点,找出|xi-xm|<h的,进入待选数组temp中
- 对temp按y值从小到大排序(这步非常重要,将O(n2)降到O(nlogn))
- 在temp数组中寻找|yi-ym|<h的i和m,计算距离并更新。注意temp已经排好序了,因此碰到一组y不符合要求的就可以跳出循环。
#include<bits/stdc++.h>
using namespace std;
struct node{
double x,y;
}a[400005],temp[400005];
double dis(node a1,node a2){
return (a1.x-a2.x)*(a1.x-a2.x)+(a1.y-a2.y)*(a1.y-a2.y);
}
bool cmp(node a1,node a2){
if(a1.x!=a2.x) return a1.x<a2.x;
return a1.y<a2.y;
}
bool cmps(node a1,node a2){
return a1.y<a2.y;
}
double merge(int l,int r){
if(l>=r) return 0;
if(l+1==r) return dis(a[l],a[r]);
int m=(l+r)/2;
double h=min(merge(l,m),merge(m,r));
int p=0;
for(int i=l;i<=r;i++){
if((a[m].x-a[i].x)*(a[m].x-a[i].x)<h){
temp[p++]=a[i];
}
}
sort(temp,temp+p,cmps);
for(int i=0;i<p;i++){
for(int j=i+1;j<p&&(temp[i].y-temp[j].y)*(temp[i].y-temp[j].y)<h;j++){
h=min(dis(temp[i],temp[j]),h);
}
}
return h;
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n;
cin>>n;
for(int i=0;i<n;i++){
cin>>a[i].x>>a[i].y;
}
sort(a,a+n,cmp);
long long ans=merge(0,n-1);
cout<<ans;
}