PrepStack · Markdown HTML

Bitmask dynamic programming

Bit manipulation and bitmask state · HTML

Formal shape

dp[mask] is the optimum after completing exactly mask; add i with next=mask|(1<<i), or remove a chosen last item in the reverse recurrence.

Recognition signals

False friends

SignalWhy it is different
Unencoded history affects the futureIf last position or remaining resource changes transitions, add that dimension.
n is too largeThe 2^n state space is itself infeasible; seek structure or another algorithm.

Core invariant

dp[mask] is optimal among all legal sequences producing exactly mask, and transitions start from already-correct smaller states.

State, transition, and processing order

ItemDefinition
StateAn array of length 2^n, with the minimum sufficient extra dimensions such as last or remaining capacity.
TransitionFor each unused i, relax dp[mask|1<<i] with dp[mask]+transition_cost(mask,i).
Frontier / orderSets progress by increasing popcount; every predecessor has one fewer item, forming a DAG.

Python skeleton

def min_order_cost(n, step_cost):
    inf = float('inf')
    dp = [inf] * (1 << n)
    dp[0] = 0
    for mask in range(1 << n):
        if dp[mask] == inf: continue
        for i in range(n):
            if mask >> i & 1: continue
            nxt = mask | (1 << i)
            dp[nxt] = min(dp[nxt], dp[mask] + step_cost(mask, i))
    return dp[-1]

Correctness sketch

  1. The empty-set base state is optimal.
  2. Every nonempty construction has a last-added item whose removal gives a smaller predecessor.
  3. Enumerating all predecessors and final choices covers every legal construction.
  4. Taking min preserves the best path to each mask, proving the full-mask optimum by induction.

Complexity

TimeSpaceParameters
Typically O(n2^n), or O(n²2^n) with a last dimensionO(2^n) or O(n2^n)n selectable items

Edge cases

Error patterns

PatternWhy it fails / fix
Insufficient stateTwo paths with the same mask cannot merge if different last items change the future.
Selecting an item twiceCheck that its bit is clear before transition.
Propagating infinitySkip unreachable states to avoid pollution or overflow.

Selection and exclusion rules

RelationTemplateBoundary
aggregation-alternativeConstraint-satisfaction backtrackingOnly an optimum/count is needed and the used set fully defines a state.
alternative0/1 or unbounded knapsack DPItem count is small while numeric capacity is huge.
aggregation-alternativePermutation backtrackingOnly an optimum over visited/matched sets is needed.
generalizationFinite-state-machine DPState is a finite automaton rather than just a set
search alternativeSubset / combination backtrackingStrong pruning avoids most masks

Original micro-example

PartDetail
ResultEight masks reuse all orderings that reach the same set.
ScenarioThree tasks have costs depending on the previously completed set.
WalkthroughMask 011 comes from 001 plus task 1 or 010 plus task 0; dp[011] retains the cheaper route.

Recall prompts

My notes