- Choose the invariant that makes a window valid or useful.
- Advance the right boundary and add the new element.
- Move the left boundary only as needed while maintaining the invariant and updating the answer.
Code notes
- 58 lines of Python from the credited upstream file abc190_f.py.
- The implementation visibly relies on sequence storage, ordered lookup.
- No explicit loop blocks detected.
Complexity
Confirm that neither pointer moves backwards; if so, the scan is usually linear apart from the window’s data-structure operations.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
12 3 4import typing5 6 7class FenwickTree:8 """Reference: https://en.wikipedia.org/wiki/Fenwick_tree"""9 10 def __init__(self, n: int = 0) -> None:11 self._n = n12 self.data = [0] * n13 14 def add(self, p: int, x: typing.Any) -> None:15 assert 0 <= p < self._n16 17 p += 118 while p <= self._n:19 self.data[p - 1] += x20 p += p & -p21 22 def sum(self, left: int, right: int) -> typing.Any:23 assert 0 <= left <= right <= self._n24 25 return self._sum(right) - self._sum(left)26 27 def _sum(self, r: int) -> typing.Any:28 s = 029 while r > 0:30 s += self.data[r - 1]31 r -= r & -r32 33 return s34 35 36def main():37 import sys38 39 input = sys.stdin.readline40 41 n = int(input())42 a = list(map(int, input().split()))43 ans = 044 fenwicktree = FenwickTree(n)45 46 for ai in a:47 ans += fenwicktree.sum(ai, n)48 fenwicktree.add(ai, 1)49 50 for k in range(n):51 print(ans)52 ans -= a[k]53 ans += n - 1 - a[k]54 55 56if __name__ == "__main__":57 main()58