- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
设 a0,...,an-1 是一个长度序列。我们可以构造区间 [0,a0], (a1,a2+a1], (a2+a1,a3+a2+a1 ],... 我将序列 a1,...,an-1 存储在 Fenwick 树中。
我问这个问题:给定一个数字 m,我如何有效地(记录 n 次)找到 m 属于哪个区间?
例如,给定 a:3、5、2、7、9、4。
分域树存储 3、8、2、17、9、13。
区间为 [0,3],(3,8],(8,10],(10,17],(17,26],(26,30)。
给定数字 9,算法应返回分域树的第 3 个索引(如果使用基于 0 的数组则为 2,如果使用基于 1 的数组则为 3)。给定数字 26,算法应返回 Fenwick 树的第 5 个索引(如果使用基于 0 的数组则为 4,如果使用基于 1 的数组则为 5)。
可能另一种数据结构更适合此操作。我使用 Fenwick Trees 是因为它们看起来简单高效。
最佳答案
我们可以得到一个 O(log n) 时间的搜索操作。诀窍是将二分搜索与前缀求和运算结合起来。
def get_total(tree, i):
total = 0
while i > 0:
total += tree[i - 1]
i -= i & (-i)
return total
def search(tree, total):
j = 1
while j < len(tree):
j <<= 1
j >>= 1
i = -1
while j > 0:
if i + j < len(tree) and total > tree[i + j]:
total -= tree[i + j]
i += j
j >>= 1
return i + 1
tree = [3, 8, 2, 17, 9, 13]
print('Intervals')
for i in range(len(tree)):
print(get_total(tree, i), get_total(tree, i + 1))
print('Searches')
for total in range(31):
print(total, search(tree, total))
输出是
Intervals
0 3
3 8
8 10
10 17
17 26
26 30
Searches
0 0
1 0
2 0
3 0
4 1
5 1
6 1
7 1
8 1
9 2
10 2
11 3
12 3
13 3
14 3
15 3
16 3
17 3
18 4
19 4
20 4
21 4
22 4
23 4
24 4
25 4
26 4
27 5
28 5
29 5
30 5
关于algorithm - Fenwick 树确定一个点落在哪个区间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34699616/
设 a0,...,an-1 是一个长度序列。我们可以构造区间 [0,a0], (a1,a2+a1], (a2+a1,a3+a2+a1 ],... 我将序列 a1,...,an-1 存储在 Fenwic
我正在尝试解决这个涉及查询分域树的问题。问题陈述如下: 这是一个来自 Hackerrank 竞赛的问题:link 给定一棵树,其中每个节点都标记为 1、2、...、n。这棵树中有多少相似对(S)? 一
假设我们连续有 n 个空框。我们将把 m 组硬币放在一些预先知道的连续盒子里。我们将第 1 组硬币放在从 i_1 到 j_1 的盒子里,第二组放在从 i_2 到 j_2 的盒子里> 等等。 将所有硬币
我的问题涉及二进制索引树(Fenwick 树)中更新步骤背后的完整推理。因此,当以一定的增量更新我们的数组时,在某个位置,更新是这样的: void updateBIT(int BITree[], in
Fenwick tree是一种数据结构,可以有效地回答主要查询: 将元素添加到数组的特定索引 update(index, value) 求1到N的元素之和 find(n) 这两个操作都在 O(log(
我想知道 Fenwick 树(或二叉索引树)是否可以修改为: 1) 增加 中所有元素的频率范围 按一定数量 2)查询的频率单例元素。 这与传统的 Fenwick 树相反,在传统的 Fenwick 树上
我最近学习了 Fenwick Tree (Binary Indexed Tree)数据结构。 在查询时,我能理解为什么要减去(idx & -idx)。但是,我真的不明白为什么在更新值时要添加 (idx
形式上,范围最小查询问题是: Given an array A[0, N-1] , Find the position of the element with the minimum value be
假设我正在跟踪 Fenwick 树中槽的使用情况。例如,让我们考虑跟踪 32 个槽,导致 Fenwick 树布局,如下图所示,其中网格中的数字表示基础数组中的索引,其中每个单元格中的值是 Fenwic
对于给定的整数数组,我们必须通过XORed 和来计算给定范围[L, R] 内的XORed 和我的意思是 Σ(Arr[i]^p) 其中 i:[L,R] 和 p 是一些数字。这可以很容易地完成,同时计算
Fenwick tree是一种允许两种操作的数据结构(您可以用更多操作来扩充它): 点更新update(index, value) 前缀和query(index) 这两个操作都在O(log(n))中其
我的意思是在 O(k log(n)) 时间内找到分域树中 kth 最小的实际频率。 如果我的数据是: Tree = [1,3,1,10,3] Actual frequency = [1,2,1,6,3
我是一名优秀的程序员,十分优秀!