Python 树状数组

树状数组(Binary Indexed Tree, BIT),又称为斐波那契堆,是一种数据结构,用于高效地解决以下问题:

  1. 单点更新:在数组的某个位置增加或减少一个值。
  2. 区间查询:查询数组中一段连续区间的元素之和。

树状数组的核心思想是使用一个数组来存储原数组的累积和,然后利用数组的偏移来快速计算区间和。这种数据结构在时间复杂度上具有优势,对于单点更新和区间查询,它们的时间复杂度都是 (O(\log n))。

以下是 Python 中实现树状数组的基本操作的示例代码:

python 复制代码
class BinaryIndexedTree:
    def __init__(self, size):
        self.size = size
        self.tree = [0] * (size + 1)

    def _parent(self, index):
        while index > 1:
            index -= index & -index
        return index

    def update(self, index, delta):
        while index <= self.size:
            self.tree[index] += delta
            index += self._parent(index)

    def query(self, index):
        result = 0
        while index > 0:
            result += self.tree[index]
            index -= self._parent(index)
        return result

# 使用示例
bit = BinaryIndexedTree(10)
bit.update(1, 5)  # 将索引1的值增加5
bit.update(3, 7)  # 将索引3的值增加7

print(bit.query(4))  # 查询索引1到4的和,应为12

在这个例子中,BinaryIndexedTree 类有三个方法:

  • __init__:初始化树状数组。
  • update:在数组的指定索引位置增加一个值。
  • query:查询从1到指定索引位置的累积和。

请注意,树状数组通常从索引1开始,而不是0,这与 Python 中列表的索引方式不同。如果你需要从0开始,可以在调用 updatequery 方法时,将索引减1。

相关推荐
ZhengEnCi1 小时前
P2M-Matplotlib折线图完全指南-从数据可视化到趋势分析的Python绘图利器
python·matlab·数据可视化
ZhengEnCi3 小时前
P2L-Matplotlib饼图完全指南-从数据可视化到图表定制的Python绘图利器
python·matlab
曲幽3 小时前
你的REST接口还在“过度投喂”数据吗?——FastAPI + GraphQL实战避坑指南
python·fastapi·web·graphql·route·cors·rest·strawberry
用户8358086187914 小时前
基于 Self-RAG 与列表级重排序的进阶 RAG 系统设计与实现
python
Warson_L20 小时前
Python `Annotated` 与 LangGraph Reducer 学习笔记
python
韩师傅20 小时前
海天线算法的前世今生
python·计算机视觉
韩师傅20 小时前
当你的甲方设备过烂,要如何快速出效果?
python·计算机视觉
Warson_L20 小时前
LangGraph的MessageState and HumanMessage
python
韩师傅21 小时前
当你的甲方吐槽天空不够蓝,你应该如何应对
python·计算机视觉
Warson_L1 天前
python的类&继承
python