Approach
Breadth-first search
For ABC291 E — Find Permutation, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 78 lines of Python from the credited upstream file abc291_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.
Use this to learn the idea, then write your own version.
12 3 4from collections import deque5from typing import List, Tuple6 7 8class TopologicalSorting:9 def __init__(self, vertex_count: int) -> None:10 self.vertex_count = vertex_count11 self.graph = [[] for _ in range(vertex_count)]12 self.indegrees = [0] * vertex_count13 14 def add_edge(self, frm: int, to: int) -> None:15 assert 0 <= frm < self.vertex_count16 assert 0 <= to < self.vertex_count17 18 self.graph[frm].append(to)19 self.indegrees[to] += 120 21 def sort(self) -> Tuple[bool, List[int]]:22 que = deque([i for i in range(self.vertex_count) if self.indegrees[i] == 0])23 results = list()24 25 if len(que) == 0:26 return False, []27 28 while que:29 if len(que) >= 2:30 return False, []31 32 vertex = que.popleft()33 results.append(vertex)34 35 for to in self.graph[vertex]:36 self.indegrees[to] -= 137 38 if self.indegrees[to] == 0:39 que.append(to)40 41 if len(results) == self.vertex_count:42 return True, results43 else:44 return False, []45 46 47def main():48 import sys49 50 input = sys.stdin.readline51 52 n, m = map(int, input().split())53 ts = TopologicalSorting(n)54 55 for _ in range(m):56 ai, bi = map(int, input().split())57 ai -= 158 bi -= 159 60 ts.add_edge(frm=ai, to=bi)61 62 is_DAG, orders = ts.sort()63 64 if is_DAG:65 ans = [0] * n66 67 for i in range(n):68 ans[orders[i]] = i + 169 70 print("Yes")71 print(*ans)72 else:73 print("No")74 75 76if __name__ == "__main__":77 main()78