Problem solution · Python

ABC396 F — Rotated Inversions

ABC396 F — Rotated Inversions: a Python solution using segment tree or range structure. Learn the idea, check the complexity, and read the full code, with credit to KATO-Hiro AtCoder Solutions.

Technique
Segment tree or range structure
Source
KATO-Hiro AtCoder Solutions
Length
112 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Segment tree or range structure

For ABC396 F — Rotated Inversions, the implementation stores interval information in a range-query data structure so updates and queries avoid rescanning the full input.

  1. Choose the aggregate stored for each interval or prefix.
  2. Build or initialize the structure from the input.
  3. Apply updates and combine the affected nodes to answer each query.

Code notes

  • 112 lines of Python from the credited upstream file abc396_f.py.
  • The implementation visibly relies on sequence storage, 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.

Source

Code and credit

This code comes from KATO-Hiro AtCoder Solutions by KATO-Hiro and is used under the CC0-1.0 licence.

Full codeABC396 F — Rotated Inversions · PythonPython
Use this to learn the idea, then write your own version.
# -*- coding: utf-8 -*-  from typing import Any  class BIT:    """Binary Indexed Tree (Fenwick Tree)     See:    https://atcoder.jp/contests/tessoku-book/submissions/34912434    """     def __init__(self, size: int) -> None:        self.size = size        self.size0 = 1 << (size.bit_length() - 1)        self.tree = [0] * (size + 1)     def add(self, index: int, value: Any) -> None:        assert 0 <= index < self.size         index += 1         while index <= self.size:            self.tree[index] += value            # self.tree[index] %= mod            index += index & -index     def get(self, index: int) -> Any:        return self.sum(index) - self.sum(index - 1)     def range_sum(self, left: int, right: int) -> Any:        assert 0 <= left <= right <= self.size         return self.sum(right - 1) - self.sum(left - 1)     def sum(self, index: int) -> Any:        index += 1        summed = 0         assert 0 <= index <= self.size         while index > 0:            summed += self.tree[index]            index -= index & -index            # summed %= mod         return summed     def lower_bound(self, value: Any) -> int:        pos = 0        plus = self.size0         while plus > 0:            if pos + plus <= self.size and self.tree[pos + plus] < value:                value -= self.tree[pos + plus]                pos += plus             plus //= 2         return pos  # See:# https://ikatakos.com/pot/programming_algorithm/dynamic_programming/inversiondef calc_inversion_number(array: list[int]) -> int:    compressed_dict = {        element: index for index, element in enumerate(sorted(set(array)))    }    compressed_list = [compressed_dict[ai] for ai in array]     size = len(compressed_list)    bit = BIT(size)    inversion_number = 0     for index, value in enumerate(compressed_list):        inversion_number += index - bit.sum(value)        bit.add(value, 1)     return inversion_number  def main():    import sys     input = sys.stdin.readline     n, m = map(int, input().split())    a = list(map(int, input().split()))    c = list()     for i, ai in enumerate(a):        c.append((ai, i))     c.sort()    count = calc_inversion_number(a)    ans = list()     for x in range(m - 1, -1, -1):        ans.append(count)         while c and c[-1][0] == x:            _, j = c.pop()            count += j            count -= n - 1 - j     print(*ans, sep="\n")  if __name__ == "__main__":    main() 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗