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 小时前
Python中itertools.product:快速生成笛卡尔积
开发语言·python
OOJO3 小时前
c++---list介绍
c语言·开发语言·数据结构·c++·算法·list
派大星~课堂5 小时前
【力扣-142. 环形链表2 ✨】Python笔记
python·leetcode·链表
Thomas.Sir5 小时前
第一章:Agent智能体开发实战之【初步认识 LlamaIndex:从入门到实操】
人工智能·python·ai·检索增强·llama·llamaindex
笨笨饿5 小时前
29_Z变换在工程中的实际意义
c语言·开发语言·人工智能·单片机·mcu·算法·机器人
艾为电子6 小时前
【技术帖】让接口不再短命:艾为 C-Shielding™ Type-C智能水汽防护技术解析
c语言·开发语言
ZTL-NPU6 小时前
Jetbrains开发ros
ide·python·pycharm·编辑器·ros·clion
棉花骑士6 小时前
【AI Agent】面向 Java 工程师的Claude Code Harness 学习指南
java·开发语言
IGAn CTOU6 小时前
PHP使用Redis实战实录2:Redis扩展方法和PHP连接Redis的多种方案
开发语言·redis·php
环黄金线HHJX.6 小时前
TSE框架配置与部署详解
开发语言·python