Overview
When the state space involves subsets of elements, we use bitmasks. A bit is 1 if an element is in the subset, 0 otherwise.
Loading...
Loading Curriculum...
Loading Subject...
Loading Topic...
Loading Lesson...
Loading Lab...
Use integer bit operations to track sets of visited elements efficiently in state representations.
When the state space involves subsets of elements, we use bitmasks. A bit is 1 if an element is in the subset, 0 otherwise.
In TSP, the state is defined by the set of visited cities and the current city we are at: `dp[mask][u]`.
From city `u` with a given `mask`, we try visiting any unvisited city `v`. The new state becomes `dp[mask | (1 << v)][v]`.
Bitwise OR `|` adds an element to the set. Bitwise AND `&` checks if an element is present. This makes state management blazing fast.