Technique
Small-to-Large Merging (DSU on tree)
When merging sets, always insert the smaller into the larger; each element moves O(log n) times, giving O(n log n) (times the set cost).
0%
mastery
0/6 solved
0/6 solved
Recognise it
The signal
per-subtree distinct counts / dominating colours
1Brute force
Build each subtree's set from scratch: O(n2).
2The observation
Repeated copying: an element that moves at least doubles its set size.
3Why it works
Each element is copied only when its set size at least doubles.
Reach for it when
- +merge maps of children
- +union-find with explicit member lists
Not when
- ×queries need order statistics per subtree beyond what a set gives
- ×offline Euler tour + BIT can be simpler for distinct counts
Practice
0/6 solved
- Count PathsCodeforces2000
- Tree RequestsCodeforces2200
- Distinct ColorsCSESHard
- Lomsat gelralCodeforces2300
- Dominant IndicesCodeforces2300
- XOR TreeCodeforces2400
Pitfalls
Misconceptions
- !swapping containers by copy instead of by pointer/move (loses the bound)
- !Two different methods share the cue: sack / DSU on tree keeps the heavy child's data and re-adds light subtrees (O(n log n), O(1) adds); merging std::sets small into large is O(n log^2 n).
Go deeper1 combinations · resources
Combinations
Small-to-Large Merging (DSU on tree)+Tree DFS (Paths & Recursion)
distinct colours per subtree; dominant colour sums
- Small-to-Large Merging (DSU on tree):
- merges child sets keeping the largest
- Tree DFS (Paths & Recursion):
- post-order over subtrees