Technique · CP 2000
Bitset Optimisation
Pack boolean DP rows or adjacency sets into machine words, so one AND/OR/shift handles 64 states at once. O(nW) becomes O(nW/64).
0/9 solved
Recognise it
The signal
boolean reachability or subset-sum where O(nW) is ~1e10 but /64 fits
1Brute force
Boolean DP cell by cell: O(nW).
2The observation
Each boolean is processed separately, though the transitions are identical shifts and ORs.
3Why it works
Bit j of the word set means state j is reachable; dp |= dp << w processes one subset-sum item.
Reach for it when
- +count reachable nodes for every vertex of a DAG with n = 5e4
- +pairs of rows sharing at least two columns (corner subgrids)
- +Hamming distances between many short bitstrings
Not when
- ×values are counts or minima, not booleans
- ×n2/64 memory too large (process in chunks)
Practice
- Reachable NodesCSESMedium
- Reachability QueriesCSESMedium
- Corner Subgrid CountCSESMedium
- Hamming DistanceCSESMedium
- School ExcursionCSESMedium
- Maximum Total Reward Using Operations IIHard
- PermuTree (hard version)Codeforces2700
- Corner Subgrid CheckCSESHard
- Border Subgrid Count ICSESHard
Pitfalls
Misconceptions
- !std::bitset needs a compile-time size (template on a maximum, or use a dynamic word array)
Go deeper4 combinations · resources
Combinations
Bitset Optimisation+Topological Sort
for every vertex of a DAG with n ~ 5e4, the number of vertices reachable from it
- Bitset Optimisation:
- reach[v] = {v} | OR of reach[child], 64 vertices per word
- Topological Sort:
- process vertices in reverse topological order
Strongly Connected Components & Condensation+Topological Sort+Bitset Optimisation
many 'can a reach b' queries on a general directed graph with n ~ 5e4
- Strongly Connected Components & Condensation:
- condense cycles so reachability lives on a DAG
- Topological Sort:
- an order for the DP over components
- Bitset Optimisation:
- per-component reachability sets
Bitset Optimisation+0/1 Knapsack
which totals are reachable, values up to 5e4, n up to 5e4
- Bitset Optimisation:
- a shift-or over word-packed bits
- 0/1 Knapsack:
- boolean reachability of sums
Union-Find (Disjoint Set)+Bitset Optimisation+0/1 Knapsack
split the vertices into two groups without breaking components, for every possible size
- Union-Find (Disjoint Set):
- component sizes
- Bitset Optimisation:
- makes the subset sum fast
- 0/1 Knapsack:
- which totals of component sizes are achievable