"""Fenwick tree (binary indexed tree).

Idea
----
Supports "add x at index i" and "sum of the first i elements" in O(log n)
each, using a single array. Index i (1-based) is responsible for the range of
length ``i & -i`` (its lowest set bit) ending at i. To query a prefix, keep
stripping the lowest set bit; to update, keep adding it.

A plain prefix-sum array answers queries in O(1) but needs O(n) per update;
a Fenwick tree balances both.

Complexity
----------
add / prefix_sum / range_sum: O(log n)
build from a list: O(n)
Space: O(n)
"""

from collections.abc import Sequence


class FenwickTree:
    def __init__(self, values: Sequence[int] | int) -> None:
        if isinstance(values, int):
            values = [0] * values
        self.n = len(values)
        self.tree = [0] + list(values)
        for i in range(1, self.n + 1):  # O(n) build
            parent = i + (i & -i)
            if parent <= self.n:
                self.tree[parent] += self.tree[i]

    def add(self, index: int, delta: int) -> None:
        """Add ``delta`` to element ``index`` (0-based)."""
        i = index + 1
        while i <= self.n:
            self.tree[i] += delta
            i += i & -i

    def prefix_sum(self, count: int) -> int:
        """Sum of the first ``count`` elements."""
        total = 0
        i = count
        while i > 0:
            total += self.tree[i]
            i -= i & -i
        return total

    def range_sum(self, left: int, right: int) -> int:
        """Sum of elements left..right inclusive (0-based)."""
        return self.prefix_sum(right + 1) - self.prefix_sum(left)
