Problem solution · Python

ABC311 C — Find it!

ABC311 C — Find it!: a Python solution using depth-first search. Learn the idea, check the complexity, and read the full code, with credit to KATO-Hiro AtCoder Solutions.

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

Depth-first search

For ABC311 C — Find it!, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.

  1. Define the state carried into one recursive or stack frame.
  2. Mark or choose the current state before exploring children.
  3. Combine child results or undo the choice when the branch finishes.

Code notes

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

Complexity

Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.

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 codeABC311 C — Find it! · PythonPython
Use this to learn the idea, then write your own version.
# -*- coding: utf-8 -*- from typing import Any, List, Tuple  # See:# https://drken1215.hatenablog.com/entry/2023/05/20/200517class CycleDetection:    pending: int = -1     def __init__(self, vertex_count: int, graph: List[List[Tuple[int, int]]]) -> None:        self.vertex_count: int = vertex_count        self.graph: List[List[Tuple[int, int]]] = graph        self.seen: List[bool] = [False] * self.vertex_count        self.finished: List[bool] = [False] * self.vertex_count        self.history: List[Any] = []     def detect(self, is_prohibit_reverse: bool = True) -> List[Any]:        pos = self.pending         for vertex in range(self.vertex_count):            if self.seen[vertex]:                continue             self.history.clear()            pos = self._dfs(vertex, self.pending, is_prohibit_reverse)             if pos != self.pending:                return self._reconstruct(pos)         return []     def _reconstruct(self, pos: int) -> List[int]:        cycle: List[Any] = []         while self.history:            cur = self.history.pop()            cycle.append(cur)             if cur == pos:                break         return cycle[::-1]     def _dfs(self, cur: int, parent: int, is_prohibit_reverse: bool = True) -> int:        self.seen[cur] = True        self.history.append(parent)         for to, id in self.graph[cur]:            if is_prohibit_reverse and (to == parent):                continue            if self.finished[to]:                continue             # Detected cycle.            if self.seen[to] and not self.finished[to]:                self.history.append(cur)                return to             pos = self._dfs(to, cur, is_prohibit_reverse)             if pos != self.pending:                return pos         self.finished[cur] = True        self.history.pop()        return self.pending  def main():    import sys     sys.setrecursionlimit(10**8)     input = sys.stdin.readline     n = int(input())    a = list(map(int, input().split()))    graph = [[] for _ in range(n)]     for i, ai in enumerate(a):        ai -= 1        graph[i].append((ai, i))     cd = CycleDetection(vertex_count=n, graph=graph)    results = cd.detect(is_prohibit_reverse=False)     print(len(results))    print(*map(lambda x: x + 1, results))  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 ↗