Approach
Breadth-first search
For ABC139 E — League, 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
- 113 lines of Python from the credited upstream file abc139_e.py.
- The implementation visibly relies on sequence storage, hash lookup, 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 """10 See:11 https:atcoder.jp/contests/abc291/submissions/3924105512 """13 14 def __init__(self, vertex_count: int) -> None:15 self.vertex_count = vertex_count16 self.graph = [[] for _ in range(vertex_count)]17 self.indegrees = [0] * vertex_count18 19 def add_edge(self, frm: int, to: int) -> None:20 """21 Args:22 frm(from) -> to: Vertex number (0-indexed).23 """24 assert 0 <= frm < self.vertex_count25 assert 0 <= to < self.vertex_count26 27 self.graph[frm].append(to)28 self.indegrees[to] += 129 30 def sort(self) -> Tuple[bool, List[int]]:31 """32 Returns:33 is_DAG: Is it DAG (Directed Acyclic Graph) ?34 orders: Order of vertices (0-indexed).35 """36 que = deque([i for i in range(self.vertex_count) if self.indegrees[i] == 0])37 results = list()38 cost = [1] * self.vertex_count39 40 if len(que) == 0:41 return False, []42 43 while que:44 45 46 47 48 vertex = que.popleft()49 results.append(vertex)50 51 for to in self.graph[vertex]:52 self.indegrees[to] -= 153 54 cost[to] = max(cost[to], cost[vertex] + 1)55 56 if self.indegrees[to] == 0:57 que.append(to)58 59 if len(results) == self.vertex_count:60 return True, cost61 else:62 return False, []63 64 65def main():66 import sys67 from collections import defaultdict68 69 input = sys.stdin.readline70 71 n = int(input())72 a = [list(map(lambda x: int(x) - 1, input().split())) for _ in range(n)]73 74 75 76 77 ids = defaultdict(int)78 id = 079 80 for i in range(n):81 for j in range(i + 1, n):82 ids[(i, j)] = id83 id += 184 85 def to_id(i, j):86 if i > j:87 i, j = j, i88 89 return ids[(i, j)]90 91 vertex_count = n * (n - 1) 292 ts = TopologicalSorting(vertex_count)93 94 for i in range(n):95 96 for j in range(n - 1):97 a[i][j] = to_id(i, a[i][j])98 99 100 for ui, vi in zip(a[i], a[i][1:]):101 ts.add_edge(vi, ui)102 103 is_DAG, dist = ts.sort()104 105 if is_DAG:106 print(max(dist))107 else:108 print(-1)109 110 111if __name__ == "__main__":112 main()113