A · International Grandmaster · 14 min

Bitmask DP

When n ≤ 20, the subset of used items is an integer mask. dp[mask] (and maybe a last index) iterates 2^n states, each in n or 2^n transitions depending on the problem.

n ≤ 20 is the constraint that *names* this technique. 2^20 ≈ 1e6, 2^20 · 20 ≈ 2e7 — legal. n = 30 is not, unless you meet-in-the-middle (2^{n/2}).

TSP: dp[mask][i] = cheapest path that visited exactly the nodes in mask and sits at i. Transition: try previous j in mask, add dist[j][i].

CSES Elevator Rides / Hamiltonian Flights. USACO Gold Bitmask DP. The WA is iterating mask in the wrong order or forgetting that i must belong to mask.

Held–Karp TSP, return to startjs
function tsp(dist) {
  const n = dist.length;
  const INF = 1e15;
  const N = 1 << n;
  const dp = Array.from({ length: N }, () => Array(n).fill(INF));
  dp[1][0] = 0; // start at 0
  for (let mask = 1; mask < N; mask++) {
    for (let i = 0; i < n; i++) {
      if (!(mask & (1 << i)) || dp[mask][i] >= INF) continue;
      for (let j = 0; j < n; j++) {
        if (mask & (1 << j)) continue;
        const next = mask | (1 << j);
        dp[next][j] = Math.min(dp[next][j], dp[mask][i] + dist[i][j]);
      }
    }
  }
  let ans = INF;
  for (let i = 0; i < n; i++) ans = Math.min(ans, dp[N - 1][i] + dist[i][0]);
  return ans;
}

TRACE

n=3, start 0. Distances all 1 except 0↔2 = 10.

mask 001, i=0

dp=0.

1 / 4

CHECK

Which loop order is safe for dp[mask] += dp[mask without i] subset sums?

CHECK

Count assignments of n people to n tasks with compatibility bits. State?

Checks 0/2

Next lesson