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。

相关推荐
前端付豪2 小时前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽3 小时前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战3 小时前
Pydantic配置管理最佳实践(一)
python
阿尔的代码屋9 小时前
[大模型实战 07] 基于 LlamaIndex ReAct 框架手搓全自动博客监控 Agent
人工智能·python
AI探索者1 天前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python
AI探索者1 天前
LangGraph 入门:构建带记忆功能的天气查询 Agent
python
FishCoderh1 天前
Python自动化办公实战:批量重命名文件,告别手动操作
python
躺平大鹅1 天前
Python函数入门详解(定义+调用+参数)
python
曲幽1 天前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama
两万五千个小时1 天前
落地实现 Anthropic Multi-Agent Research System
人工智能·python·架构