- 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
- 88 lines of Python from the credited upstream file abc355_d.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.
Use this to learn the idea, then write your own version.
12 3 4class SegmentTree:5 def __init__(self, size):6 self.size = 2 ** ((size - 1).bit_length())7 self.tree = [0] * (2 * self.size)8 9 def add(self, i, x):10 i += self.size11 self.tree[i] += x12 13 while i > 1:14 self.tree[i >> 1] = self.tree[i] + self.tree[i ^ 1]15 i >>= 116 17 def query(self, l, r):18 l += self.size19 r += self.size20 s = 021 22 while l < r:23 if l & 1:24 s += self.tree[l]25 l += 126 if r & 1:27 r -= 128 s += self.tree[r]29 30 l >>= 131 r >>= 132 33 return s34 35 36from bisect import bisect_right37from typing import List38 39 40def bisect_le(sorted_array: List[int], value: int):41 """Find the largest element <= x and its index, or None if it doesn't exist."""42 43 if sorted_array[0] <= value:44 index: int = bisect_right(sorted_array, value) - 145 46 return index, sorted_array[index]47 48 return None, None49 50 51def main():52 import sys53 54 input = sys.stdin.readline55 56 n = int(input())57 lr = [tuple(map(int, input().split())) for _ in range(n)]58 lr = sorted(lr)59 l = [li for li, _ in lr]60 61 compressed = {x: i for i, x in enumerate(sorted(set(l)))}62 st = SegmentTree(len(compressed))63 64 for i in range(n):65 li, _ = lr[i]66 st.add(compressed[li], 1)67 68 ans = 069 70 for j in range(n - 1):71 lj, rj = lr[j]72 st.add(compressed[lj], -1)73 74 75 _, value = bisect_le(l, rj)76 77 if value is None:78 continue79 80 count = st.query(0, compressed[value] + 1)81 ans += count82 83 print(ans)84 85 86if __name__ == "__main__":87 main()88