- 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
- 108 lines of Python from the credited upstream file abc351_f.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 3from typing import Any4 5 6def compress_coordinate(elements: list) -> dict:7 """Means that reduce the numerical value while maintaining the magnitude8 relationship.9 10 Args:11 elements: list of integer numbers (greater than -1).12 13 Returns:14 A dictionary's items ((original number, compressed number) pairs).15 16 Landau notation: O(n log n)17 """18 19 20 21 compressed_list = sorted(set(elements))22 return {element: index for index, element in enumerate(compressed_list)}23 24 25class BIT:26 """Binary Indexed Tree (Fenwick Tree)27 28 See:29 https:atcoder.jp/contests/tessoku-book/submissions/3491243430 """31 32 def __init__(self, size: int) -> None:33 self.size = size34 self.size0 = 1 << (size.bit_length() - 1)35 self.tree = [0] * (size + 1)36 37 def add(self, index: int, value: Any) -> None:38 assert 0 <= index < self.size39 40 index += 141 42 while index <= self.size:43 self.tree[index] += value44 45 index += index & -index46 47 def get(self, index: int) -> Any:48 return self.sum(index) - self.sum(index - 1)49 50 def range_sum(self, left: int, right: int) -> Any:51 assert 0 <= left <= right <= self.size52 53 return self.sum(right - 1) - self.sum(left - 1)54 55 def sum(self, index: int) -> Any:56 index += 157 summed = 058 59 assert 0 <= index <= self.size60 61 while index > 0:62 summed += self.tree[index]63 index -= index & -index64 65 66 return summed67 68 def lower_bound(self, value: Any) -> int:69 pos = 070 plus = self.size071 72 while plus > 0:73 if pos + plus <= self.size and self.tree[pos + plus] < value:74 value -= self.tree[pos + plus]75 pos += plus76 77 plus = 278 79 return pos80 81 82def main():83 import sys84 85 input = sys.stdin.readline86 87 n = int(input())88 a = list(map(int, input().split()))89 c = compress_coordinate(a)90 count = BIT(n)91 summed = BIT(n)92 ans = 093 94 for ai in a:95 ci = c[ai]96 97 ans += count.range_sum(0, ci) * ai98 ans -= summed.range_sum(0, ci)99 100 count.add(ci, 1)101 summed.add(ci, ai)102 103 print(ans)104 105 106if __name__ == "__main__":107 main()108