Approach
Sorting and greedy selection
For ABC241 D — Sequence Query, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 175 lines of Python from the credited upstream file abc241_d.py.
- The implementation visibly relies on sequence storage, ordered lookup.
- No explicit loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
12 3 45import math6from bisect import bisect_left, bisect_right, insort7from typing import Generic, Iterable, Iterator, TypeVar, Union, List8T = TypeVar('T')9 10class SortedMultiset(Generic[T]):11 BUCKET_RATIO = 5012 REBUILD_RATIO = 17013 14 def _build(self, a=None) -> None:15 "Evenly divide `a` into buckets."16 if a is None: a = list(self)17 size = self.size = len(a)18 bucket_size = int(math.ceil(math.sqrt(size / self.BUCKET_RATIO)))19 self.a = [a[size * i bucket_size : size * (i + 1) bucket_size] for i in range(bucket_size)]20 21 def __init__(self, a: Iterable[T] = []) -> None:22 "Make a new SortedMultiset from iterable. / O(N) if sorted / O(N log N)"23 a = list(a)24 if not all(a[i] <= a[i + 1] for i in range(len(a) - 1)):25 a = sorted(a)26 self._build(a)27 28 def __iter__(self) -> Iterator[T]:29 for i in self.a:30 for j in i: yield j31 32 def __reversed__(self) -> Iterator[T]:33 for i in reversed(self.a):34 for j in reversed(i): yield j35 36 def __len__(self) -> int:37 return self.size38 39 def __repr__(self) -> str:40 return "SortedMultiset" + str(self.a)41 42 def __str__(self) -> str:43 s = str(list(self))44 return "{" + s[1 : len(s) - 1] + "}"45 46 def _find_bucket(self, x: T) -> List[T]:47 "Find the bucket which should contain x. self must not be empty."48 for a in self.a:49 if x <= a[-1]: return a50 return a51 52 def __contains__(self, x: T) -> bool:53 if self.size == 0: return False54 a = self._find_bucket(x)55 i = bisect_left(a, x)56 return i != len(a) and a[i] == x57 58 def count(self, x: T) -> int:59 "Count the number of x."60 return self.index_right(x) - self.index(x)61 62 def add(self, x: T) -> None:63 "Add an element. / O(√N)"64 if self.size == 0:65 self.a = [[x]]66 self.size = 167 return68 a = self._find_bucket(x)69 insort(a, x)70 self.size += 171 if len(a) > len(self.a) * self.REBUILD_RATIO:72 self._build()73 74 def discard(self, x: T) -> bool:75 "Remove an element and return True if removed. / O(√N)"76 if self.size == 0: return False77 a = self._find_bucket(x)78 i = bisect_left(a, x)79 if i == len(a) or a[i] != x: return False80 a.pop(i)81 self.size -= 182 if len(a) == 0: self._build()83 return True84 85 def lt(self, x: T) -> Union[T, None]:86 "Find the largest element < x, or None if it doesn't exist."87 for a in reversed(self.a):88 if a[0] < x:89 return a[bisect_left(a, x) - 1]90 91 def le(self, x: T) -> Union[T, None]:92 "Find the largest element <= x, or None if it doesn't exist."93 for a in reversed(self.a):94 if a[0] <= x:95 return a[bisect_right(a, x) - 1]96 97 def gt(self, x: T) -> Union[T, None]:98 "Find the smallest element > x, or None if it doesn't exist."99 for a in self.a:100 if a[-1] > x:101 return a[bisect_right(a, x)]102 103 def ge(self, x: T) -> Union[T, None]:104 "Find the smallest element >= x, or None if it doesn't exist."105 for a in self.a:106 if a[-1] >= x:107 return a[bisect_left(a, x)]108 109 def __getitem__(self, x: int) -> T:110 "Return the x-th element, or IndexError if it doesn't exist."111 if x < 0: x += self.size112 if x < 0: raise IndexError113 for a in self.a:114 if x < len(a): return a[x]115 x -= len(a)116 raise IndexError117 118 def index(self, x: T) -> int:119 "Count the number of elements < x."120 ans = 0121 for a in self.a:122 if a[-1] >= x:123 return ans + bisect_left(a, x)124 ans += len(a)125 return ans126 127 def index_right(self, x: T) -> int:128 "Count the number of elements <= x."129 ans = 0130 for a in self.a:131 if a[-1] > x:132 return ans + bisect_right(a, x)133 ans += len(a)134 return ans135 136 137def main():138 import sys139 140 input = sys.stdin.readline141 142 q = int(input())143 s = SortedMultiset()144 ans = list()145 146 for _ in range(q):147 qi = list(map(int, input().split()))148 x = qi[1]149 150 if qi[0] == 1:151 s.add(x)152 elif qi[0] == 2:153 k = qi[2]154 count = s.index_right(x)155 156 if count >= k:157 ans.append(s[count - k])158 else:159 ans.append(-1)160 else:161 k = qi[2]162 count = s.index(x)163 remain = len(s) - count164 165 if remain >= k:166 ans.append(s[count + k - 1])167 else:168 ans.append(-1)169 170 print('\n'.join(map(str, ans)))171 172 173if __name__ == "__main__":174 main()175