Graph Theory37 sections · 1633 units
Open in Course

Subordinates - Implementation

(C++ code)

Read input, build adjacency list, DFS from node 11:

sub = array of size n

function dfs(u, p):
    sub[u] = 1
    for v in adj[u]:
        if v == p:
            continue
        dfs(v, u)
        sub[u] = sub[u] + sub[v]

dfs(1, 0)
for i from 1 to n:
    print sub[i] - 1

This runs in O(n)O(n) time and uses O(n)O(n) space.