- Define the priority key and whether the smallest or largest item should lead.
- Push each candidate when it becomes eligible.
- Discard stale entries when necessary and process the best live candidate.
Code notes
- 111 lines of Python from the credited upstream file abc223_d.py.
- The implementation visibly relies on sequence storage, ordered lookup, work queue.
- No explicit loop blocks detected.
Complexity
Count heap pushes and pops; each normally contributes a logarithmic factor in the heap size.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
12 3 4from heapq import heapify, heappop, heappush5from typing import List, Optional6 7 8class DeletableHeapq:9 """Alternatives to ordered set (set) in C++.10 Landau notation: O(log(n))11 See:12 https:qiita.com/physharp/items/f9229ab879cac9a944d713 https:prd-xxx.hateblo.jp/entry/2019/06/24/23584414 """15 16 def __init__(self, descending_order=False) -> None:17 self.q: List[int] = [] 18 self.p: List[int] = [] 19 self.descending_order = descending_order20 self.sign = -1 if descending_order else 121 22 def build(self, a: List[int]) -> None:23 """Build a priority-queue q from an array."""24 25 if self.descending_order:26 a = [-ai for ai in a]27 28 self.q = a29 heapify(self.q)30 31 def push(self, number: int) -> None:32 """Add a number to the priority-queue."""33 heappush(self.q, number * self.sign)34 35 def erase(self, number: int) -> None:36 """Pseudo-erase a number to the priority-queue."""37 heappush(self.p, number * self.sign)38 self.clean()39 40 def clean(self) -> None:41 """Remove top elements from q, p."""42 43 while self.p and self.q[0] == self.p[0]:44 heappop(self.q)45 heappop(self.p)46 47 def pop(self, exc=None) -> Optional[int]:48 """Pop a top value from the priority-queue."""49 self.clean()50 51 if self.q:52 return heappop(self.q) * self.sign53 return exc54 55 def top(self, exc=None) -> Optional[int]:56 """Get a top value from the priority-queue.57 Landau notation: O(1)58 Note:59 descending_order=False: min value.60 descending_order=True : max value.61 """62 self.clean()63 64 if self.q:65 return self.q[0] * self.sign66 return exc67 68 69def main():70 import sys71 72 input = sys.stdin.readline73 74 n, m = map(int, input().split())75 graph = [[] for _ in range(n)]76 degree = [0] * n77 78 for _ in range(m):79 ai, bi = map(int, input().split())80 ai -= 181 bi -= 182 83 graph[ai].append(bi)84 degree[bi] += 185 86 hq = DeletableHeapq()87 ans = list()88 89 for index, d in enumerate(degree):90 if d == 0:91 hq.push(index)92 93 while hq.q:94 hi = hq.pop()95 ans.append(hi + 1)96 97 for g in graph[hi]:98 degree[g] -= 199 100 if degree[g] == 0:101 hq.push(g)102 103 if len(ans) == n:104 print(*ans)105 else:106 print(-1)107 108 109if __name__ == "__main__":110 main()111