hdu 2966 In case of failure ( kd-tree(只有查询) 模板题)
题目链接:hdu2966
题意:
给出二维平面上n(1E5)个点,问对于每个点,其他距离其最近的点的距离是多少。
思路:
kd-tree 裸题。
1/* ***********************************************
2Author :111qqz
3Created Time :2017年10月08日 星期日 18时43分38秒
4File Name :2996.cpp
5************************************************ */
6
7#include <cstdio>
8#include <cstring>
9#include <iostream>
10#include <algorithm>
11#include <vector>
12#include <queue>
13#include <set>
14#include <map>
15#include <string>
16#include <cmath>
17#include <cstdlib>
18#include <ctime>
19#define PB push_back
20#define fst first
21#define sec second
22#define lson l,m,rt<<1
23#define rson m+1,r,rt<<1|1
24#define ms(a,x) memset(a,x,sizeof(a))
25typedef long long LL;
26#define pi pair < int ,int >
27#define MP make_pair
28
29using namespace std;
30const double eps = 1E-8;
31const int dx4[4]={1,0,0,-1};
32const int dy4[4]={0,-1,1,0};
33const int inf = 0x3f3f3f3f;
34const int N=1E5+7;
35int n;
36struct Point
37{
38 LL x,y;
39}p[N],p2[N]; //复制一份,因为nth_element的时候会把顺序打乱。
40bool dv[N]; //划分方式
41bool cmpx( const Point & p1, const Point &p2)
42{
43 return p1.x<p2.x;
44}
45bool cmpy(const Point &p1 ,const Point &p2)
46{
47 return p1.y<p2.y;
48}
49LL getDis( Point a, Point b)
50{
51 return (a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y);
52}
53void build ( int l,int r)
54{
55 if (l>r) return;
56 int mid = (l+r) >> 1;
57 int minx = min_element(p+l,p+r,cmpx)->x;
58 int miny = min_element(p+l,p+r,cmpy)->y;
59 int maxx = max_element(p+l,p+r,cmpx)->x;
60 int maxy = max_element(p+l,p+r,cmpy)->y;
61 dv[mid] = maxx-minx >= maxy-miny;
62 nth_element(p+l,p+mid,p+r+1,dv[mid]?cmpx:cmpy);
63 build(l,mid-1);
64 build(mid+1,r);
65
66}
67LL res;
68void query( int l,int r,Point a)
69{
70 if (l>r) return;
71 int mid = (l+r)>>1;
72 LL dis = getDis(a,p[mid]);
73 //printf("%lld %lld %lld %lld %lld\n",a.x,a.y,p[mid].x,p[mid].y,dis);
74 if (dis>0) res = min(res,dis);//判掉和自己的距离。
75 LL d = dv[mid]?(a.x-p[mid].x):(a.y-p[mid].y);
76 int l1=l,r1=mid-1,l2=mid+1,r2=r;
77 if (d>0) swap(l1,l2),swap(r1,r2);
78 query(l1,r1,a); //左儿子
79 if (d*d<res) query(l2,r2,a);//如果与分界线相交,则也要查询右儿子。
80}
81
82int main()
83{
84 #ifndef ONLINE_JUDGE
85 freopen("./in.txt","r",stdin);
86 #endif
87 int T;
88 cin>>T;
89 while (T--)
90 {
91 scanf("%d",&n);
92 for ( int i = 1 ; i <= n ; i++) {
93 scanf("%lld %lld",&p[i].x,&p[i].y);
94 p2[i] = p[i];
95 }
96 build (1,n);
97 for ( int i = 1 ; i <= n ; i++)
98 {
99 res = 1LL<<60;
100 query(1,n,p2[i]);
101 printf("%lld\n",res);
102 }
103
104 }
105 #ifndef ONLINE_JUDGE
106 fclose(stdin);
107 #endif
108 return 0;
109}