Source code for titan_pylib.data_structures.cumulative_sum.cumulative_sum

 1from typing import Iterable
 2
 3
[docs] 4class CumulativeSum: 5 """1次元累積和です。""" 6 7 def __init__(self, a: Iterable[int], e: int = 0): 8 """ 9 :math:`O(n)` です。 10 11 Args: 12 a (Iterable[int]): ``CumulativeSum`` を構築する配列です。 13 e (int): 単位元です。デフォルトは ``0`` です。 14 """ 15 a = list(a) 16 n = len(a) 17 acc = [e] * (n + 1) 18 for i in range(n): 19 acc[i + 1] = acc[i] + a[i] 20 self.n = n 21 self.acc = acc 22 self.a = a 23
[docs] 24 def pref(self, r: int) -> int: 25 """区間 ``[0, r)`` の演算結果を返します。 26 :math:`O(1)` です。 27 28 Args: 29 r (int): インデックスです。 30 """ 31 assert ( 32 0 <= r <= self.n 33 ), f"IndexError: {self.__class__.__name__}.pref({r}), n={self.n}" 34 return self.acc[r]
35
[docs] 36 def all_sum(self) -> int: 37 """区間 `[0, n)` の演算結果を返します。 38 :math:`O(1)` です。 39 40 Args: 41 l (int): インデックスです。 42 r (int): インデックスです。 43 """ 44 return self.acc[-1]
45
[docs] 46 def sum(self, l: int, r: int) -> int: 47 """区間 `[l, r)` の演算結果を返します。 48 :math:`O(1)` です。 49 50 Args: 51 l (int): インデックスです。 52 r (int): インデックスです。 53 """ 54 assert ( 55 0 <= l <= r <= self.n 56 ), f"IndexError: {self.__class__.__name__}.sum({l}, {r}), n={self.n}" 57 return self.acc[r] - self.acc[l]
58 59 prod = sum 60 all_prod = all_sum 61 62 def __getitem__(self, k: int) -> int: 63 assert ( 64 -self.n <= k < self.n 65 ), f"IndexError: {self.__class__.__name__}[{k}], n={self.n}" 66 return self.a[k] 67 68 def __len__(self) -> int: 69 return len(self.a) 70 71 def __str__(self) -> str: 72 return str(self.acc) 73 74 __repr__ = __str__