Problem solution · Python

CCC 2024 S4 - Painting Roads

CCC 2024 S4 - Painting Roads: 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
35 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 2024 S4 - Painting Roads, 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

  • 35 lines of Python from the credited upstream file ccc24s4.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 2024 S4 - Painting Roads · 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/ccc24s4 import syssys.setrecursionlimit(int(2e6)+5)input = sys.stdin.readline def dfs(cur, red):    vis[cur] = True    for nxt in graph[cur]:        if not vis[nxt]:            if red:                ans[roadMap[(cur, nxt)]] = "R"            else:                ans[roadMap[(cur, nxt)]] = "B"            dfs(nxt, not red) n, m = map(int, input().split())graph = [[] for i in range(n+1)]roadMap = {}ans = ["G"]*m for i in range(m):    u, v = map(int, input().split())    graph[u].append(v)    graph[v].append(u)    roadMap[(u, v)] = i    roadMap[(v, u)] = i vis = [False]*(n+1)for u in range(1, n+1):    if not vis[u]: dfs(u, True)print("".join(ans))

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 ↗