Approach
Depth-first search
For ABC404 D — Goin' to the Zoo, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 61 lines of Python from the credited upstream file abc404_d.py.
- The implementation visibly relies on sequence storage, ordered lookup.
- No explicit loop blocks detected, together with recursive traversal.
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.
Use this to learn the idea, then write your own version.
12 3 4import re5 6 7def main():8 import sys9 10 sys.setrecursionlimit(10**8)11 12 input = sys.stdin.readline13 14 n, m = map(int, input().split())15 c = list(map(int, input().split()))16 b = [[] for _ in range(n)]17 18 for i in range(m):19 ki, *ai = map(int, input().split())20 21 for aij in ai:22 aij -= 123 b[aij].append(i)24 25 inf = 10**1826 ans = inf27 28 def dfs(i, a):29 nonlocal ans30 31 if i == n:32 freq = [0] * m33 34 for ai, bi in zip(a, b):35 for bij in bi:36 freq[bij] += ai37 38 ok = all(f >= 2 for f in freq)39 40 if ok:41 candidate = 042 43 for ai, ci in zip(a, c):44 candidate += ai * ci45 46 ans = min(ans, candidate)47 48 return49 50 for j in range(3):51 a.append(j)52 dfs(i + 1, a)53 a.pop()54 55 dfs(0, [])56 print(ans)57 58 59if __name__ == "__main__":60 main()61