标签:dea stack out ring 存储 tmp been custom about
求平面最近点对。
裸的$KD-tree$。
我们用线性结构来存储这颗树,其主要思想是将一段区间内的元素中间那个元素作为根节点,其余作为左右子树,用个决策函数来划分。
询问的时候就比较暴力...其主要就是通过根节点以及其与子树的关系来优化搜索过程。
1 //It is made by Awson on 2017.11.25 2 #include <map> 3 #include <set> 4 #include <cmath> 5 #include <ctime> 6 #include <queue> 7 #include <stack> 8 #include <cstdio> 9 #include <string> 10 #include <vector> 11 #include <cstdlib> 12 #include <cstring> 13 #include <iostream> 14 #include <algorithm> 15 #define LL long long 16 #define LD long double 17 #define Max(a, b) ((a) > (b) ? (a) : (b)) 18 #define Min(a, b) ((a) < (b) ? (a) : (b)) 19 #define dist(a, b, c, d) (sqr(a-c)+sqr(b-d)) 20 #define sqr(x) ((x)*(x)) 21 #define y1 yy 22 #define count COUNT 23 using namespace std; 24 const int N = 1e5; 25 26 int n, now; 27 LL ans; 28 struct tt { 29 LL x[2]; 30 bool operator < (const tt &b) const { 31 return x[now] < b.x[now]; 32 } 33 }a[N+5], b[N+5]; 34 struct KD_tree { 35 void build(int l, int r, int flag) { 36 if (l >= r) return; 37 now = flag; 38 int mid = (l+r)>>1; 39 nth_element(a+l, a+mid, a+r+1); 40 build(l, mid-1, flag^1); build(mid+1, r, flag^1); 41 } 42 void query(int l, int r, int flag, tt p) { 43 if (l > r) return; 44 int mid = (l+r)>>1; 45 LL tmp = dist(a[mid].x[0], a[mid].x[1], p.x[0], p.x[1]); 46 if (tmp && tmp < ans) ans = tmp; 47 if (a[mid].x[flag] < p.x[flag]) { 48 query(mid+1, r, flag^1, p); 49 if (ans > sqr(a[mid].x[flag]-p.x[flag])) 50 query(l, mid-1, flag^1, p); 51 }else { 52 query(l, mid-1, flag^1, p); 53 if (ans > sqr(a[mid].x[flag]-p.x[flag])) 54 query(mid+1, r, flag^1, p); 55 } 56 } 57 }kd; 58 59 void work() { 60 scanf("%d", &n); 61 for (int i = 1; i <= n; i++) { 62 scanf("%lld%lld", &a[i].x[0], &a[i].x[1]); 63 b[i] = a[i]; 64 } 65 kd.build(1, n, 0); 66 for (int i = 1; i <= n; i++) { 67 ans = 1e18; 68 kd.query(1, n, 0, b[i]); 69 printf("%lld\n", ans); 70 } 71 } 72 int main() { 73 int t; cin >> t; 74 while (t--) work(); 75 return 0; 76 }
标签:dea stack out ring 存储 tmp been custom about
原文地址:http://www.cnblogs.com/NaVi-Awson/p/7895069.html