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。

相关推荐
孟健14 小时前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞16 小时前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽18 小时前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers
敏编程1 天前
一天一个Python库:jsonschema - JSON 数据验证利器
python
前端付豪1 天前
LangChain记忆:通过Memory记住上次的对话细节
人工智能·python·langchain
databook1 天前
ManimCE v0.20.1 发布:LaTeX 渲染修复与动画稳定性提升
python·动效
花酒锄作田1 天前
使用 pkgutil 实现动态插件系统
python
前端付豪2 天前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽2 天前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战2 天前
Pydantic配置管理最佳实践(一)
python