Binary Indexed Tree(二进制索引树、树状数组)
来源:互联网 发布:php addslashes和gpc 编辑:程序博客网 时间:2024/06/06 15:52
今天在刷leetcode时遇到了一道可以使用Binary Indexed Tree的题,以前未接触过,记下来以便以后复习
Binary Indexed Tree(树状数组)是一种树型数据结构,用于动态维护一个序列的前缀和。在实践中,它几乎总是用数组来实现;另外,由于代码易于记忆,它的树型结构很容易被忽略掉。它的中文名称“树状数组”很可能是因为以上两个特点得来。
低位(LowBit)
LowBit,即2进制数中从最低位开始连续0的位数的关于2的幂,其值LowBit(x)=x∧-x(x&-x,x and -x)。也就是上文所说的2^k
LowBit(x)显然就是not x中最低的是0的那一位,(not x)+1的那一位则会变成1,其更低的位全部变成0,而更高的位不变。由于更高的位就是原数取反,和原数求and的值为0,最低位就是唯一的是1的位了。所以LowBit(x)=x and((not x)+1)。 同时not x=-x-1,所以LowBit(x)=x and (-x)。
上图就是一个长度为16的数组的BIT,index(16)就表示落在16以内的个数,同时index(16)=sum(num[1]+num[2]+...+num[16])=index(8)+index(12)+index(14)+num[16]
即用index[i]表示从数据数组num中某一处一直到num[i]共2^k个元素的总和
int read(int idx){int sum = 0;while (idx > 0){sum += tree[idx];idx -= (idx & -idx);}return sum;}
举例: idx=13,sum=0:
改变一些位置的频率并更新tree
void update(int idx ,int val){while (idx <= MaxVal){tree[idx] += val;idx += (idx & -idx);}}
与普通数组相比在查找时时间复杂度变成logn,但增加了插入花销(普通数组插入复杂度为O(1),BIT为O(logn))
315. Count of Smaller Numbers After Self
题目为找出数组中每个数字后面比这个数小的数的个数
我们可以在将原数组排序后把问题变成每个数的索引在BIT中有多少比他小的索引,从左向右进行扫描,每扫描完成一个将其在BIT中的占位从BIT中减去,即可使用nlogn的复杂度完成任务。
315代码,搜索130
307. Range Sum Query - Mutable
题目要求求一个区间内数值的总和,是BIT的长项之一,直接构建BIT,将数组放到相应的索引内,区间值就是大索引的和减去小索引的和
307代码
相关链接:http://www.nocow.cn/index.php/%E6%A0%91%E7%8A%B6%E6%95%B0%E7%BB%84
http://www.xuebuyuan.com/1396639.html
- Binary Indexed Tree(二进制索引树、树状数组)
- binary indexed tree 二分索引树 树状数组
- 树状数组 ( Binary Indexed Tree,BIT,二分索引树 )
- 树状数组 ( Binary Indexed Tree,BIT,二分索引树 )
- 树状数组(Binary Indexed Tree)
- 树状数组(Binary Indexed Tree)
- 树状数组(Binary Indexed Tree)
- Binary indexed tree(树状数组)
- 树状数组(Binary Indexed Tree)
- 树状数组 Binary Indexed Tree
- 树状数组(binary indexed tree)
- 树状数组 Binary Indexed Tree
- 树状数组/Binary Indexed Tree/Fenwick Tree
- 树状数组(Binary Indexed Trees,二分索引树)
- 树状数组(Binary Indexed Tree)
- POJ 2352 树状数组(Binary Indexed Tree)
- POJ 2481 树状数组(Binary Indexed Tree)
- poj3067 树状数组(Binary Indexed Tree)
- 协同过滤
- c++第七次实验
- DrawerLayout + NavigationView 侧滑菜单,ViewPager + Fragment 快速构建主界面
- ubuntu 打不开商店怎么办
- LeetCode--No.19--Remove Nth Node From End Of List
- Binary Indexed Tree(二进制索引树、树状数组)
- c++第七次实验(项目2:最大公约和和最小公倍数)
- 作业七
- C++第7次作业
- Volley工作原理与设计模式
- [Hackerrank] Floyd : City of Blinding Lights
- Volley网络请求框架
- Volley缓存原理
- c++第七次上机实验