Proofs: Sum over subsets dynamic programming
These are the human proofs of Sum over subsets dynamic programming, at full length.
SOS DP computes the sum over all submasks for every mask full
This proof shows: correctness.
Let , let be a commutative monoid, and let be the input. For a mask write for bit of , and when for every .
Definition. For , let
A submask in may differ from only on bits to . So and .
Lemma 1. Let .
(a) If , then .
(b) If , then is the disjoint union of and .
Proof. (a) Let . Then and give , so agrees with on bits to and . The other inclusion holds because the condition of is stronger than that of .
(b) Let , which is with bit cleared. Let . If , then agrees with on bits to , so . If , then (bit of both is 0 and the other bits of are those of ), and agrees with on bits to , so . Conversely, each member of is in ; and each satisfies and agrees with on bits to , so . Every member of has bit equal to 1, and every member of has it equal to 0, so the union is disjoint.
Theorem. SOS-DP returns with for every .
Proof. We prove this invariant of the loop of line L2.
(I) Before the pass with index , for : for every mask .
Initialization. Line L1 sets , and , so (I) holds for .
Maintenance. Assume (I) before pass , with . Let be the array before the pass. In the pass, line L5 writes only to entries with , and only once to each, in the iteration for that . The entry it reads, , has bit of its index equal to 0, so no iteration of this pass writes it, and it equals at the time of the read, in any order of the masks.
- If , the pass does not change , and by Lemma 1(a) and (I), .
- If , line L5 sets by (I). By Lemma 1(b), the two index sets are disjoint and their union is ; since is associative and commutative, the sum is .
So (I) holds before pass .
Termination. The loop of line L2 runs for and stops. Then (I) holds for , and is the set of all submasks of . Line L6 returns .
Cost. Pass runs line L4 for all masks and line L5 for the masks with bit set. So there are tests and exactly additions, and the time is when each test and addition costs .
Supersets and the inverse. The superset version is the same proof with each mask complemented: the map (on bits) turns submasks into supermasks, the test "bit is 1" into "bit is 0", and into . For the Möbius transform over a commutative group, pass with subtraction is the inverse of pass with addition (it maps to on each pair , and the pairs of a pass are disjoint), and the passes for distinct bits commute because each acts on one coordinate of the cube ; so running all subtracting passes inverts SOS-DP.