Technique
Sum over Subsets (SOS) DP
For every mask compute an aggregate over all its submasks (or supermasks) in O(B * 2^B) by prefix-summing one bit dimension at a time.
0/4 solved
Recognise it
The signal
for each x count y with y & x == y (or x & y == 0)
1Brute force
Enumerate submasks of every mask: O(3^B).
2The observation
Submask enumeration: each mask is a B-dimensional 0/1 coordinate, so prefix sums per dimension suffice.
3Why it works
After processing bits 0..i, F[mask] sums over submasks that differ from mask only in bits 0..i.
Reach for it when
- +values up to 220
- +AND/OR convolutions
Not when
- ×B > ~23 (memory/time)
- ×aggregation is not associative/commutative
Practice
- SOS Bit ProblemCSESMedium
- Love-HateCodeforces2400
- Compatible NumbersCodeforces2200
- And Subset CountCSESHard
Pitfalls
Misconceptions
- !looping masks outside bits (must be bits outside)
Go deeper2 combinations · resources
Combinations
Sum over Subsets (SOS) DP+Bit Tricks & Bitmasking
for each x count y with x | y == x, x & y == y, or x & y == 0
- Sum over Subsets (SOS) DP:
- aggregates over submasks for all masks
- Bit Tricks & Bitmasking:
- mask representation
Randomised Sampling Arguments+Sum over Subsets (SOS) DP
find the largest set of items liked by at least half the people, with m <= 60 items but <= 15 liked per person
- Randomised Sampling Arguments:
- a random friend belongs to the optimal half-liked set with probability >= 1/2
- Sum over Subsets (SOS) DP:
- for that friend's <= 15 liked currencies, count supersets over masks