Approach
Depth-first search
For CCC 2016 S3 - Phonomenal Reviews, 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
- 45 lines of Python from the credited upstream file ccc16s3.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.
123 45 6import sys7sys.setrecursionlimit(int(2e5+5))8input = sys.stdin.readline9 10def prune(cur, pre):11 global pho12 for nxt in graph[cur]:13 if nxt != pre:14 prune(nxt, cur)15 if pho[nxt]:16 pho[cur] = True17 18def dfs(cur, pre, dis):19 global node1, diameter20 for nxt in graph[cur]:21 if nxt != pre and pho[nxt]:22 dfs(nxt, cur, dis+1)23 if dis > diameter:24 diameter = dis25 node1 = cur26 27n, m = map(int, input().split())28pho = [False] * n29root = -130for item in list(map(int, input().split())):31 root = item32 pho[item] = True33graph = [[] for i in range(n)]34for i in range(n-1):35 a, b = map(int, input().split())36 graph[a].append(b)37 graph[b].append(a)38prune(root, -1)39tot = sum(pho)40diameter = 041node1 = root42dfs(root, -1, 0)43dfs(node1, -1, 0)44print(2*(tot-1) - diameter)45