Time Complexity: O(N)\mathcal O(N)

For more information about centroids and how to find/use them, see their module.

MAX_N = 200000
g = [[] for i in range(MAX_N + 1)] # graph
subtree_size = [0 for i in range(MAX_N + 1)] # size of subtree
def dfs_size(curr: int, parent: int) -> None:
"""calculates all subtree sizes (sum of child sizes + 1)"""
subtree_size[curr] = 1
for child in g[curr]:
if child != parent:

Join the USACO Forum!

Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!