Problem solution · Python

ABC217 E — Sorting Queries

ABC217 E — Sorting Queries: a Python solution using breadth-first search. Learn the idea, check the complexity, and read the full code, with credit to KATO-Hiro AtCoder Solutions.

Technique
Breadth-first search
Source
KATO-Hiro AtCoder Solutions
Length
99 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

Breadth-first search

For ABC217 E — Sorting Queries, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.

  1. Model each valid configuration as a state and each legal move as an edge.
  2. Seed the queue with the starting state and mark it immediately.
  3. Expand each state once, recording distance or reachability for unseen neighbours.

Code notes

  • 99 lines of Python from the credited upstream file abc217_e.py.
  • The implementation visibly relies on sequence storage, ordered lookup, work queue.
  • No explicit loop blocks detected.

Complexity

Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.

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 codeABC217 E — Sorting Queries · PythonPython
Use this to learn the idea, then write your own version.
# -*- coding: utf-8 -*-  from heapq import heapify, heappop, heappushfrom typing import List, Optional  class DeletableHeapq:    """Alternatives to ordered set (set) in C++.    Landau notation: O(log(n))    See:    https://qiita.com/physharp/items/f9229ab879cac9a944d7    https://prd-xxx.hateblo.jp/entry/2019/06/24/235844    """     def __init__(self, descending_order=False) -> None:        self.q: List[int] = []  # Body        self.p: List[int] = []  # For deleting        self.descending_order = descending_order        self.sign = -1 if descending_order else 1     def build(self, a: List[int]) -> None:        """Build a priority-queue q from an array."""         if self.descending_order:            a = [-ai for ai in a]         self.q = a        heapify(self.q)     def push(self, number: int) -> None:        """Add a number to the priority-queue."""        heappush(self.q, number * self.sign)     def erase(self, number: int) -> None:        """Pseudo-erase a number to the priority-queue."""        heappush(self.p, number * self.sign)        self.clean()     def clean(self) -> None:        """Remove top elements from q, p."""         while self.p and self.q[0] == self.p[0]:            heappop(self.q)            heappop(self.p)     def pop(self, exc=None) -> Optional[int]:        """Pop a top value from the priority-queue."""        self.clean()         if self.q:            return heappop(self.q) * self.sign        return exc     def top(self, exc=None) -> Optional[int]:        """Get a top value from the priority-queue.        Landau notation: O(1)        Note:        descending_order=False: min value.        descending_order=True : max value.        """        self.clean()         if self.q:            return self.q[0] * self.sign        return exc  def main():    from collections import deque    import sys     input = sys.stdin.readline     q = int(input())    d = deque()    hq = DeletableHeapq()        for _ in range(q):        qi = list(map(int, input().split()))         if qi[0] == 1:            d.append(qi[1])        elif qi[0] == 2:            if hq.q:                h = hq.pop()                print(h)            else:                di = d.popleft()                print(di)        else:            while d:                di = d.popleft()                hq.push(di)  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 ↗