← 中文资源

简体中文版本

Fenwick 树支持更新后的区间和

Fenwick 树用 index & -index 跳跃维护前缀和:单点更新与区间查询都是 O(log n),改一个元素后无需重扫整个数组。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

16
12
20

实现说明

Fenwick 树支持更新后的区间和的核心是类 FenwickTree和函数 __init__、add、prefix_sum、range_sum。 while position <= self.size 反复执行,循环体之外没有别的重复。

使用要点

  • 值得导入的表面是 add;周围的辅助代码对片段是私有的。

常见问题

有第三方依赖吗?

没有。依赖清单是空的,代码只用标准库。 文件在加载时定义 __init__、add、prefix_sum。

主要签名是 def add(self, position: int, delta: int) -> None

核心语句

def add(self, position: int, delta: int) -> None:
    while position <= self.size:
        self.tree[position] += delta
        position += position & -position
def __init__(self, size: int) -> None:
    self.size = size
    self.tree = [0] * (size + 1)
def range_sum(self, left: int, right: int) -> int:
    return self.prefix_sum(right) - self.prefix_sum(left - 1)

代码示例

class FenwickTree:
    """Prefix sums with point updates in O(log n).

    Positions are 1-based; index 0 is a sentinel.
    """

    def __init__(self, size: int) -> None:
        self.size = size
        self.tree = [0] * (size + 1)

    def add(self, position: int, delta: int) -> None:
        while position <= self.size:
            self.tree[position] += delta
            position += position & -position

    def prefix_sum(self, position: int) -> int:
        total = 0
        while position > 0:
            total += self.tree[position]
            position -= position & -position
        return total

    def range_sum(self, left: int, right: int) -> int:
        return self.prefix_sum(right) - self.prefix_sum(left - 1)


fenwick = FenwickTree(8)
for position, score in enumerate([5, 2, 9, 1, 7], start=1):
    fenwick.add(position, score)

print(fenwick.range_sum(1, 3))  # 5 + 2 + 9 = 16
fenwick.add(3, -4)              # score at position 3 drops 9 -> 5
print(fenwick.range_sum(1, 3))  # recomputed without rescanning values
print(fenwick.prefix_sum(5))    # 5 + 2 + 5 + 1 + 7 = 20