Graph Theory37 sections · 1633 units
Open in Course

Lomsat gelral - Algorithm

(Small-to-large on maps)

First DFS: compute subtree sizes so you can identify the heavy child. Second DFS: for node vv, process all children. Take the frequency map from the largest child. For each smaller child, iterate its map and merge counts into the large map.

Update count[color] for each color. After merging all children, increment count[color[v]]. Then scan the entire map to find the max frequency and sum all colors with that frequency. Store the sum as the answer for vv.

This runs in O(nlog⁡n)O(n \log n) time and uses O(n)O(n) space.