1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
| #include<iostream> #include<algorithm> #include<vector> #include<cmath> using namespace std; const int k = 2; const int maxn = 100; int cmp_dim; vector<vector<int> >dat; struct Node { int value[k]; int dim; Node* parent=NULL; Node* left_ch=NULL; Node* right_ch=NULL; }kdnode[maxn]; bool cmp(const Node& a,const Node& b) { return a.value[cmp_dim] < b.value[cmp_dim]; }
Node* build(int l,int r,int d) { if (l > r)return NULL; int m; cmp_dim = d; if ((l + r) & 1)m = 1+(l + r) >> 1; else m = (l + r) >> 1; nth_element(kdnode + l, kdnode + m, kdnode + r + 1,cmp); kdnode[m].dim = d; Node* lch = build(l, m-1, (d + 1) % k); if (lch != NULL) { lch->parent = kdnode + m; kdnode[m].left_ch = lch; } Node* rch = build(m + 1, r, (d + 1) % k); if (rch != NULL) { rch->parent = kdnode + m; kdnode[m].right_ch = rch; } return kdnode + m; }
int distance(int* a,int* b) { int res = 0; for (int i = 0; i < k; i++) res += (a[i]-b[i])*(a[i]-b[i]); return res; }
Node* root; int min_dis; Node* nearest;
Node* the_one(int* arr) { int d = 0; Node* r=root; Node* tmp=r; while (r != NULL) { tmp = r; if (r->value[d] > arr[d]) { r = r->left_ch; } else r = r->right_ch; d = (d + 1) % k; } min_dis = distance(arr, tmp->value); nearest = tmp; return tmp; }
void search_son(Node* son, int* tar) { if (son == NULL) return; if (distance(son->value, tar) < min_dis) { nearest = son; min_dis = distance(son->value, tar); } if (pow(son->value[son->dim] - tar[son->dim], 2) < min_dis) { search_son(son->left_ch, tar); search_son(son->right_ch, tar); } else { if (son->value[son->dim] > tar[son->dim]) search_son(son->left_ch, tar); else search_son(son->right_ch, tar); } }
void search_all(Node* now,int tar[k]) { Node* par = now->parent; while (now->parent != NULL) { now = now->parent; if (distance(tar, now->value) < min_dis) { nearest = now; min_dis = distance(tar, now->value); } Node* son; if (pow(now->value[now->dim], 2) < min_dis) { if (now->value[now->dim] > tar[now->dim]) son = now->right_ch; else son = now->left_ch; search_son(son,tar); } } } int main() { int n = 6; dat.push_back({ 2,3 }); dat.push_back({ 5,4 }); dat.push_back({ 9,6 }); dat.push_back({ 4,7 }); dat.push_back({ 8,1 }); dat.push_back({ 7,2 }); for (int i = 0; i < n; i++) { for (int j = 0; j < k; j++) { kdnode[i].value[j] = dat[i][j]; } } root=build(0, n - 1, 0); int a[2] = { 8,2 }; Node* now = the_one(a); search_all(now, a); cout << distance(nearest->value, a); return 0; }
|