Graph Theory37 sections · 1633 units
Open in Course

Codeforces 580C Kefa and Park - Implementation

Coding the logic

Here's the solution:

answer := 0

function dfs(u, parent, consecutive_cats):
    if has_cat[u]:
        consecutive_cats := consecutive_cats + 1
    else:
        consecutive_cats := 0

    if consecutive_cats > m:
        return

    is_leaf := true
    for each neighbor v of u:
        if v != parent:
            is_leaf := false
            dfs(v, u, consecutive_cats)

    if is_leaf:
        answer := answer + 1

dfs(1, -1, 0)
print(answer)

Start from vertex 11 with no parent and zero consecutive cats. If a cat appears, increment the streak. If not, reset to zero. Stop exploring if the streak exceeds mm. At leaves, increment the answer.

Time: O(n)O(n). Space: O(n)O(n) for the recursion stack.