K-D Tree
这篇随笔是对Wikipedia上 k-d tree 词条的摘录, 我认为对该词条解释相当生动详细, 是不可多得的好文.
Overview
A $k$-d tree (short for $k$-dimensional tree) is a binary space-partitioning tree for organizing points in a $k$-dimensional space. $k$-d trees are a useful data structure for searches involving a multidimensional search key.
Construction
The canonical method of $k$-d tree construction has the following constraints:
- As one moves down the tree, one cycles through the axes used to select the splitting planes.
- Points are inserted by selecting the median of the points being put into the subtree, with respect to their coordinates in the axis being used to create the splitting plane.
This method leads to a balanced $k$-d tree, in which each leaf node is approximately the same distance from the root. However, balanced trees are not necessarily optimal for all applications.
Nearest Neighboring Search
Terms:
- the split dimensions
- the splitting (hyper)plane
- "current best"
The **nearest neighbour ** (NN) search algorithm aims to find the point in the tree that is nearest to a given point. This search can be done efficiently by using the tree properties to quickly eliminate large portions of the search space.
Searching for a nearest neighbour in a $k$-d tree proceeds as follows:
- Starting with the root node, the algorithm moves down the tree recursively.
- Once the algorithm reaches a leaf node, it saves that node point as "current best"
- The algorithm unwinds the recursion of the tree, performing the following steps at each node:
- If the current node is closer than the current best, then it becomes the current best.
- The algorithm checks whether there could be any points on the other side of the splitting plane that are closer to the search point than the current best. In concept, this is done by intersecting the splitting hyperplane with a hypersphere around the the search point that has a radius equal to the current nearest distance. Since the hyperplanes are all axis-aligned this is implemented as a simple comparison to see whether the distance between the splitting coordinate of the search point and current node is less than the distance (overall coordinates) from the search point to the current best.
- If the hypersphere crosses the plane, there could be nearer points on the other side of the plane, so the algorithm must move down the other branch of the tree from the current node looking for closer points, following the same recursive process as the entire search.
- If the hypersphere doesn't intersect the splitting plane, then the algorithm continues walking up the tree, and the entire branch on the other side of that node is eliminated.
Generally, the algorithm uses squared distances for comparison to avoid computing square roots. Additionally, it can save computation by holding the squared current best distance in a variable for computation.
The algorithm can be extended in several ways by simple modifications. If can provide the $k $ nearest neighbors to a point by maintaining $k$ current bests instead of just one. A branch is only eliminated when $k$ points have been found and the branch cannot have points closer than any of the $k$ current bests.
Implementation
$k$ 近临 ($k$NN)
#include <bits/stdc++.h>
#define lson id<<1
#define rson id<<1|1
#define sqr(x) (x)*(x)
using namespace std;
using LL=long long;
const int N=5e4+5;
// K-D tree: a special case of binary space partitioning trees
int DIM, idx;
struct Node{
int key[5];
bool operator<(const Node &rhs)const{
return key[idx]<rhs.key[idx];
}
void read(){
for(int i=0; i<DIM; i++)
scanf("%d", key+i);
}
LL dis2(const Node &rhs)const{
LL res=0;
for(int i=0; i<DIM; i++)
res+=sqr(key[i]-rhs.key[i]);
return res;
}
void out(){
for(int i=0; i<DIM; i++)
printf("%d%c", key[i], i==DIM-1?'\n':' ');
}
}p[N];
Node a[N<<2]; // K-D tree
bool f[N<<2];
// [l, r)
void build(int id, int l, int r, int dep)
{
if(l==r) return; // error-prone
f[id]=true, f[lson]=f[rson]=false;
// select axis based on depth so that axis cycles through all valid values
idx=dep%DIM;
int mid=l+r>>1;
// sort point list and choose median as pivot element
nth_element(p+l, p+mid, p+r);
a[id]=p[mid];
build(lson, l, mid, dep+1);
build(rson, mid+1, r, dep+1);
}
using P=pair<LL,Node>;
priority_queue<P> que;
// multidimensional search key
void query(const Node &p, int id, int m, int dep){
int dim=dep%DIM;
int x=lson, y=rson;
// left: <, right >=
if(p.key[dim]>=a[id].key[dim])
swap(x, y);
if(f[x]) query(p, x, m, dep+1);
P cur{p.dis2(a[id]), a[id]};
if(que.size()<m){
que.push(cur);
}
else if(cur.first<que.top().first){
que.pop();
que.push(cur);
}
if(f[y] && sqr(a[id].key[dim]-p.key[dim])<que.top().first)
query(p, y, m, dep+1);
}
说明:
bool数组f[], 表示一个完全二叉树中的某个节点是否存在, 也可不用完全二叉树的表示法, 而用两个数组lson[]和rson[]表示, 这样的好处还有: 节省空间, 数组可以只开到节点数的2倍.- 区间采用左闭右开表示.
K-D Tree的更多相关文章
- 第46届ICPC澳门站 K - Link-Cut Tree // 贪心 + 并查集 + DFS
原题链接:K-Link-Cut Tree_第46屆ICPC 東亞洲區域賽(澳門)(正式賽) (nowcoder.com) 题意: 要求一个边权值总和最小的环,并从小到大输出边权值(2的次幂):若不存在 ...
- AOJ DSL_2_C Range Search (kD Tree)
Range Search (kD Tree) The range search problem consists of a set of attributed records S to determi ...
- Size Balance Tree(SBT模板整理)
/* * tree[x].left 表示以 x 为节点的左儿子 * tree[x].right 表示以 x 为节点的右儿子 * tree[x].size 表示以 x 为根的节点的个数(大小) */ s ...
- HDU3333 Turing Tree(线段树)
题目 Source http://acm.hdu.edu.cn/showproblem.php?pid=3333 Description After inventing Turing Tree, 3x ...
- POJ 3321 Apple Tree(树状数组)
Apple Tree Time Limit: 2000MS Memory Lim ...
- CF 161D Distance in Tree 树形DP
一棵树,边长都是1,问这棵树有多少点对的距离刚好为k 令tree(i)表示以i为根的子树 dp[i][j][1]:在tree(i)中,经过节点i,长度为j,其中一个端点为i的路径的个数dp[i][j] ...
- Segment Tree 扫描线 分类: ACM TYPE 2014-08-29 13:08 89人阅读 评论(0) 收藏
#include<iostream> #include<cstdio> #include<algorithm> #define Max 1005 using nam ...
- Size Balanced Tree(SBT) 模板
首先是从二叉搜索树开始,一棵二叉搜索树的定义是: 1.这是一棵二叉树: 2.令x为二叉树中某个结点上表示的值,那么其左子树上所有结点的值都要不大于x,其右子树上所有结点的值都要不小于x. 由二叉搜索树 ...
- hdu 5274 Dylans loves tree(LCA + 线段树)
Dylans loves tree Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Othe ...
随机推荐
- MPI+WIN10并行试运行
系统:2015 win10专业版 x64 MPI安装包:mpich2-1.4.1p1-win-x86-64.man 将后缀改为.msi 以管理员身份安装 安装过程一路默认,注意<behappy为 ...
- Mybatis解析动态sql原理分析
前言 废话不多说,直接进入文章. 我们在使用mybatis的时候,会在xml中编写sql语句. 比如这段动态sql代码: <update id="update" parame ...
- PRML读书会第十四章 Combining Models(committees,Boosting,AdaBoost,决策树,条件混合模型)
主讲人 网神 (新浪微博: @豆角茄子麻酱凉面) 网神(66707180) 18:57:18 大家好,今天我们讲一下第14章combining models,这一章是联合模型,通过将多个模型以某种形式 ...
- js时间倒计时
看了网上的其他的例子,觉得写的都有点复杂,不好理解,于是自己动手写了个. 本来想封装成jquery插件,但是觉得因为功能很简单,没有必要做成jquery插件,引用的时候不需要引入jqery库,这里直接 ...
- 理解Android安全机制
本文从Android系统架构着手,分析Android的安全机制以SE Android,最后给出一些Android安全现状和常见的安全解决方案. 1.Android系统架构 Android采用分层的系统 ...
- Code Review 五问五答
Code Review 是什么? Code Review即代码审查,程序猿相互审核对方的代码. Code Review能获得什么好处? 提高代码可维护性 你写的代码不再只有编译器看了,你得写出审核人能 ...
- Bootstrap系列 -- 5. 文本对齐方式
一. 文本对齐样式 .text-left:左对齐 .text-center:居中对齐 .text-right:右对齐 .text-justify:两端对齐 二. 使用方式 <p class=&q ...
- mysql中导入txt文件
1 windows 下 mysql导入txt文件(使用mysql的workbench) load data local infile 'path' into table table_name fiel ...
- android服务之启动方式
服务有两种启动方式 通过startService方法来启动 通过bindService来开启服务 布局文件 在布局文件中我们定义了四个按键来测试这两种方式来开启服务的不同 <?xml versi ...
- apache 多端口配置和虚拟主机配置
1 打开httpd.conf文件 2 添加端口监听 (找到Lisen 80 在后面添加 Listen 端口号 如Listen 1112) port =>你的端口 project_name=> ...