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。

相关推荐
zone77392 小时前
004:RAG 入门-LangChain读取PDF
后端·python·面试
zone77392 小时前
005:RAG 入门-LangChain读取表格数据
后端·python·agent
树獭非懒16 小时前
AI大模型小白手册|Embedding 与向量数据库
后端·python·llm
唐叔在学习19 小时前
就算没有服务器,我照样能够同步数据
后端·python·程序员
曲幽21 小时前
FastAPI流式输出实战与避坑指南:让AI像人一样“边想边说”
python·ai·fastapi·web·stream·chat·async·generator·ollama
Flittly21 小时前
【从零手写 AI Agent:learn-claude-code 项目实战笔记】(1)The Agent Loop (智能体循环)
python·agent
vivo互联网技术1 天前
ICLR2026 | 视频虚化新突破!Any-to-Bokeh 一键生成电影感连贯效果
人工智能·python·深度学习
敏编程1 天前
一天一个Python库:virtualenv - 隔离你的Python环境,保持项目整洁
python
喝茶与编码1 天前
Python异步并发控制:asyncio.gather 与 Semaphore 协同设计解析
后端·python