- Choose the aggregate stored for each interval or prefix.
- Build or initialize the structure from the input.
- Apply updates and combine the affected nodes to answer each query.
Code notes
- 107 lines of Python from the credited upstream file abc221_e.py.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
- No explicit loop blocks detected.
Complexity
Count the build once, then multiply the logarithmic update or query path by the number of operations.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
12 3import typing4 5 6class FenwickTree:7 """Reference: https://en.wikipedia.org/wiki/Fenwick_tree"""8 9 def __init__(self, n: int = 0, mod=None) -> None:10 self._n = n11 self.data = [0] * n12 self.mod = mod13 14 def add(self, p: int, x: typing.Any) -> None:15 assert 0 <= p < self._n16 17 p += 118 19 while p <= self._n:20 self.data[p - 1] += x21 22 if self.mod is not None:23 self.data[p - 1] %= self.mod24 25 p += p & -p26 27 def sum(self, left: int, right: int) -> typing.Any:28 """[left, right)"""29 assert 0 <= left <= right <= self._n30 31 return self._sum(right) - self._sum(left)32 33 def _sum(self, r: int) -> typing.Any:34 s = 035 36 while r > 0:37 s += self.data[r - 1]38 39 if self.mod is not None:40 s %= self.mod41 42 r -= r & -r43 44 return s45 46 47def compress_coordinate(elements: list) -> dict:48 """Means that reduce the numerical value while maintaining the magnitude49 relationship.50 51 Args:52 elements: list of integer numbers (greater than -1).53 54 Returns:55 A dictionary's items ((original number, compressed number) pairs).56 57 Landau notation: O(n log n)58 """59 60 61 62 compressed_list = sorted(set(elements))63 return {element: index for index, element in enumerate(compressed_list)}64 65 66def main():67 import sys68 69 input = sys.stdin.readline70 71 n = int(input())72 a = list(map(int, input().split()))73 74 75 76 77 78 79 80 81 82 c = compress_coordinate(a)83 size = len(c.keys())84 mod = 99824435385 ft = FenwickTree(size + 1, mod)86 inv = pow(2, mod - 2, mod) 87 two, inv_two = 1, 188 ans = 089 90 for ai in a:91 d = c[ai]92 ans += two * ft.sum(0, d + 1) 93 ans %= mod94 95 two *= 296 two %= mod97 inv_two *= inv98 inv_two %= mod99 100 ft.add(d, inv_two)101 102 print(ans)103 104 105if __name__ == "__main__":106 main()107