hdu 2966 In case of failure ( kd-tree(只有查询) 模板题)

题目链接:hdu2966  

题意:

给出二维平面上n(1E5)个点,问对于每个点,其他距离其最近的点的距离是多少。

思路:

kd-tree 裸题。

kd-tree 学习笔记

/* ***********************************************
Author :111qqz
Created Time :2017年10月08日 星期日 18时43分38秒
File Name :2996.cpp
************************************************ */
 1#include <cstdio>
 2#include <cstring>
 3#include <iostream>
 4#include <algorithm>
 5#include <vector>
 6#include <queue>
 7#include <set>
 8#include <map>
 9#include <string>
10#include <cmath>
11#include <cstdlib>
12#include <ctime>
13#define PB push_back
14#define fst first
15#define sec second
16#define lson l,m,rt<<1
17#define rson m+1,r,rt<<1|1
18#define ms(a,x) memset(a,x,sizeof(a))
19typedef long long LL;
20#define pi pair < int ,int >
21#define MP make_pair
 1using namespace std;
 2const double eps = 1E-8;
 3const int dx4[4]={1,0,0,-1};
 4const int dy4[4]={0,-1,1,0};
 5const int inf = 0x3f3f3f3f;
 6const int N=1E5+7;
 7int n;
 8struct Point
 9{
10    LL x,y;
11}p[N],p2[N]; //复制一份,因为nth_element的时候会把顺序打乱。
12bool dv[N]; //划分方式
13bool cmpx( const Point & p1, const Point &p2)
14{
15    return p1.x<p2.x;
16}
17bool cmpy(const Point &p1 ,const Point &p2)
18{
19    return p1.y<p2.y;
20}
21LL getDis( Point a, Point b)
22{
23    return (a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y);
24}
25void build ( int l,int r)
26{
27    if (l>r) return;
28    int mid = (l+r) >> 1;
29    int minx = min_element(p+l,p+r,cmpx)->x;
30    int miny = min_element(p+l,p+r,cmpy)->y;
31    int maxx = max_element(p+l,p+r,cmpx)->x;
32    int maxy = max_element(p+l,p+r,cmpy)->y;
33    dv[mid] = maxx-minx >= maxy-miny;
34    nth_element(p+l,p+mid,p+r+1,dv[mid]?cmpx:cmpy);
35    build(l,mid-1);
36    build(mid+1,r);
 1}
 2LL res;
 3void query( int l,int r,Point a)
 4{
 5    if (l>r) return;
 6    int mid = (l+r)>>1;
 7    LL dis = getDis(a,p[mid]);
 8    //printf("%lld %lld  %lld %lld    %lld\n",a.x,a.y,p[mid].x,p[mid].y,dis);
 9    if (dis>0) res = min(res,dis);//判掉和自己的距离。 
10    LL d = dv[mid]?(a.x-p[mid].x):(a.y-p[mid].y);
11    int l1=l,r1=mid-1,l2=mid+1,r2=r;
12    if (d>0) swap(l1,l2),swap(r1,r2);
13    query(l1,r1,a); //左儿子
14    if (d*d<res) query(l2,r2,a);//如果与分界线相交,则也要查询右儿子。
15}
 1int main()
 2{
 3    #ifndef  ONLINE_JUDGE 
 4    freopen("./in.txt","r",stdin);
 5  #endif
 6    int T;
 7    cin>>T;
 8    while (T--)
 9    {
10        scanf("%d",&n);
11        for ( int i = 1 ; i <= n ; i++) {
12        scanf("%lld %lld",&p[i].x,&p[i].y);
13        p2[i] = p[i];
14        }
15        build (1,n);
16        for ( int i = 1 ; i <= n ; i++)
17        {
18        res = 1LL<<60;
19        query(1,n,p2[i]);
20        printf("%lld\n",res);
21        }
1    }
2  #ifndef ONLINE_JUDGE  
3  fclose(stdin);
4  #endif
5    return 0;
6}