Set operations as bit operations
Representing a subset of as an integer makes every set operation :
| Set operation | Notation | Bitwise |
|---|---|---|
| Intersection | A & B | |
| Union | A | B | |
| Symmetric difference | A ^ B | |
| Difference | A & ~B | |
| Complement | ~A & ((1<<n)-1) | |
| Subset test | (A & B) == A, or (A | B) == B | |
| Disjoint | (A & B) == 0 | |
| Cardinality | __builtin_popcount(A) | |
| Add element | A | (1<<i) | |
| Remove element | A & ~(1<<i) | |
| Toggle | A ^ (1<<i) | |
| Membership | A >> i & 1 | |
| Empty / universal set | / | 0 / (1<<n)-1 |
See Bit Operations and Enumerating Submasks.
Inclusion-exclusion
long long total = 0;
for (int mask = 1; mask < (1 << n); mask++) {
long long size = intersectionSize(mask);
total += (__builtin_popcount(mask) & 1) ? size : -size;
}. When the sets are βdivisible by β, the signs are exactly the MΓΆbius function, and the sum can be sieved instead of enumerated β see MΓΆbius Function.
Complementary counting is the same idea used backwards: count what you do not want and subtract. Often much easier.
Notation reference
| Symbol | Meaning |
|---|---|
| , | element of, not an element of |
| , | subset, proper subset |
| , , , | union, intersection, difference, symmetric difference |
| cardinality | |
| or | power set β all subsets |
| Cartesian product | |
| all -element subsets | |
| the empty set | |
| naturals, integers, rationals, reals, complexes | |
| , | integers mod , the field of order |
| , | floor, ceiling |
| , | sum, product |
| , | for all, there exists |
| , | implies, if and only if |
| congruent (modular) | |
| , | divides, does not divide |
| XOR (or direct sum) | |
| minimum excluded non-negative integer | |
| Iverson bracket: 1 if holds, else 0 |
The Iverson bracket is worth adopting: writing inside a sum makes MΓΆbius manipulations mechanical.
Counting sets
| Quantity | Count |
|---|---|
| Subsets of an -set | |
| -subsets | |
| Ordered pairs with | |
| Ordered pairs with | |
| Partitions into non-empty blocks | (Bell) |
| Partitions into exactly blocks | (Stirling 2nd kind) |
| Chains | ordered set partitions |
| Antichains in the subset lattice | Dedekind numbers (no closed form) |
The identity is the one that matters computationally: it is exactly why submask enumeration over all masks is .
The subset lattice
Subsets ordered by form a lattice β a hypercube graph . Consequences:
- SOS DP is a zeta transform over this lattice.
- Gray code is a Hamiltonian path on it.
- MΓΆbius inversion on the lattice is the inclusion-exclusion formula.
- The maximum antichain has size (Spernerβs theorem).
See also: Bit Operations Β· Combinatorics Β· MΓΆbius Function