hdu 2966 In case of failure ( kd-tree(只有查询) 模板题)
题目链接:hdu2966
题意:
给出二维平面上n(1E5)个点,问对于每个点,其他距离其最近的点的距离是多少。
思路:
kd-tree 裸题。
/* ***********************************************
Author :111qqz
Created Time :2017年10月08日 星期日 18时43分38秒
File Name :2996.cpp
************************************************ */
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <cmath>
#include <cstdlib>
#include <ctime>
#define PB push_back
#define fst first
#define sec second
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define ms(a,x) memset(a,x,sizeof(a))
typedef long long LL;
#define pi pair < int ,int >
#define MP make_pair
using namespace std;
const double eps = 1E-8;
const int dx4[4]={1,0,0,-1};
const int dy4[4]={0,-1,1,0};
const int inf = 0x3f3f3f3f;
const int N=1E5+7;
int n;
struct Point
{
LL x,y;
}p[N],p2[N]; //复制一份,因为nth_element的时候会把顺序打乱。
bool dv[N]; //划分方式
bool cmpx( const Point & p1, const Point &p2)
{
return p1.x<p2.x;
}
bool cmpy(const Point &p1 ,const Point &p2)
{
return p1.y<p2.y;
}
LL getDis( Point a, Point b)
{
return (a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y);
}
void build ( int l,int r)
{
if (l>r) return;
int mid = (l+r) >> 1;
int minx = min_element(p+l,p+r,cmpx)->x;
int miny = min_element(p+l,p+r,cmpy)->y;
int maxx = max_element(p+l,p+r,cmpx)->x;
int maxy = max_element(p+l,p+r,cmpy)->y;
dv[mid] = maxx-minx >= maxy-miny;
nth_element(p+l,p+mid,p+r+1,dv[mid]?cmpx:cmpy);
build(l,mid-1);
build(mid+1,r);
}
LL res;
void query( int l,int r,Point a)
{
if (l>r) return;
int mid = (l+r)>>1;
LL dis = getDis(a,p[mid]);
//printf("%lld %lld %lld %lld %lld\n",a.x,a.y,p[mid].x,p[mid].y,dis);
if (dis>0) res = min(res,dis);//判掉和自己的距离。
LL d = dv[mid]?(a.x-p[mid].x):(a.y-p[mid].y);
int l1=l,r1=mid-1,l2=mid+1,r2=r;
if (d>0) swap(l1,l2),swap(r1,r2);
query(l1,r1,a); //左儿子
if (d*d<res) query(l2,r2,a);//如果与分界线相交,则也要查询右儿子。
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("./in.txt","r",stdin);
#endif
int T;
cin>>T;
while (T--)
{
scanf("%d",&n);
for ( int i = 1 ; i <= n ; i++) {
scanf("%lld %lld",&p[i].x,&p[i].y);
p2[i] = p[i];
}
build (1,n);
for ( int i = 1 ; i <= n ; i++)
{
res = 1LL<<60;
query(1,n,p2[i]);
printf("%lld\n",res);
}
}
#ifndef ONLINE_JUDGE
fclose(stdin);
#endif
return 0;
}