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.
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;
}Checks 0/2