Problem solution · Python

CCC 2016 S3 - Phonomenal Reviews

CCC 2016 S3 - Phonomenal Reviews: a Python solution using depth-first search. Learn the idea, check the complexity, and read the full code, with credit to CCCSolutions.

Technique
Depth-first search
Source
CCCSolutions
Length
45 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 CCC 2016 S3 - Phonomenal Reviews, 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

  • 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.

Source

Code and credit

This code comes from CCCSolutions by CCCSolutions contributors · Milliken Mills High School and is used under the MIT licence.

Full codeCCC 2016 S3 - Phonomenal Reviews · PythonPython
Use this to learn the idea, then write your own version.
# By Oscar Zhou, Abbey Park High School# This solution still requires commented explanations. Please feel free to add them! # https://dmoj.ca/problem/ccc16s3 import syssys.setrecursionlimit(int(2e5+5))input = sys.stdin.readline def prune(cur, pre):    global pho    for nxt in graph[cur]:        if nxt != pre:            prune(nxt, cur)            if pho[nxt]:                pho[cur] = True def dfs(cur, pre, dis):    global node1, diameter    for nxt in graph[cur]:        if nxt != pre and pho[nxt]:            dfs(nxt, cur, dis+1)    if dis > diameter:        diameter = dis        node1 = cur n, m = map(int, input().split())pho = [False] * nroot = -1for item in list(map(int, input().split())):    root = item    pho[item] = Truegraph = [[] for i in range(n)]for i in range(n-1):    a, b = map(int, input().split())    graph[a].append(b)    graph[b].append(a)prune(root, -1)tot = sum(pho)diameter = 0node1 = rootdfs(root, -1, 0)dfs(node1, -1, 0)print(2*(tot-1) - diameter) 

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 ↗