01A subset is just an integer
Number the items 0..n−1. A subset is an n-bit number: bit j is 1 when item j is in the set. With 4 cities, 1011₂ = 11 means cities 1, 2 and 4 (bits 0, 1, 3).
All set operations become one CPU instruction:
- is j in the set?
mask & (1 << j) - add j:
mask | (1 << j); remove j:mask & ~(1 << j) - the full set:
(1 << n) − 1; all subsets:for mask in 0 .. 2ⁿ−1
So an array indexed by mask, dp[mask], stores one answer per subset: 2ⁿ entries. For n = 20 that is about a million, comfortable. For n = 30 it is a billion, too many. That limit tells you when to think of bitmask DP: the constraints say n ≤ 20 or so, and the problem needs to remember “which ones are used”.
Note that if mask′ adds an element to mask, then mask′ > mask, so increasing order is a valid fill order.