Graph Theory37 sections · 1633 units
Open in Course

CSES 1674 Subordinates - Implementation

Code with adjacency list

Here is the implementation:

size = array of size n + 1

function dfs(v, parent):
    size[v] = 1
    for u in adj[v]:
        if u != parent:
            dfs(u, v)
            size[v] = size[v] + size[u]

dfs(1, -1)

for v from 1 to n:
    print size[v] - 1

Time: O(n)O(n) (visit each node once). Space: O(n)O(n) for the size array and recursion stack.