To solve problems using State Compression Dynamic Programming (DP), we leverage bitmasks to represent subsets or configurations efficiently. This approach is ideal when the number of elements (n) is small (typically ≤20, as 2²⁰ ≈ 1e6 is manageable).
Key Concepts
- Bitmask: An integer where each bit indicates whether an element is included in the subset (1 = included, 0 = excluded). For example, mask
101(binary) represents the subset {0,2} for n=3. - DP State: Usually
dp[mask]ordp[mask][u](additional parameter like current position). The value ofdp[mask]could be the minimal cost, maximum value, or count of valid configurations.
Example: Traveling Salesman Problem (TSP)
Given n cities, find the shortest path to visit all cities exactly once and return to the starting city.
Step 1: Define State
dp[mask][u]: Minimal cost to reach city u after visiting all cities in mask (mask includes u).
Step 2: Initialize
dp[1<<start][start] = 0 (only visited the starting city, cost = 0).
Step 3: Transition
For each mask, and each city u in mask:
- For each city
vnot in mask:new_mask = mask | (1<<v)dp[new_mask][v] = min(dp[new_mask][v], dp[mask][u] + cost[u][v])
Step 4: Compute Answer
The answer is the minimum of dp[full_mask][u] + cost[u][start] for all u (full_mask = (1<<n)-1).
Sample Code (TSP)
n = 4
cost = [
[0,1,2,3],
[1,0,4,5],
[2,4,0,6],
[3,5,6,0]
]
INF = float('inf')
# dp[mask][u] = minimal cost to reach u with mask
dp = [[INF]*n for _ in range(1<<n)]
dp[1<<0][0] = 0 # start at city 0
for mask in range(1<<n):
for u in range(n):
if not (mask & (1<<u)):
continue # u not in mask
for v in range(n):
if mask & (1<<v):
continue # v already in mask
new_mask = mask | (1<<v)
if dp[new_mask][v] > dp[mask][u] + cost[u][v]:
dp[new_mask][v] = dp[mask][u] + cost[u][v]
# Find minimal path back to start (0)
full_mask = (1<<n)-1
ans = INF
for u in range(n):
ans = min(ans, dp[full_mask][u] + cost[u][0])
print(ans) # Output:14
Common Use Cases
- Subset Problems: Maximize value of a subset with constraints (e.g., dependencies between items).
- Grid Tiling: Cover a grid with tiles (e.g., dominoes) using row-wise state masks.
- Permutations: Find valid permutations with specific rules (e.g., no adjacent duplicates).
State compression DP is a powerful technique for problems where the state can be represented as a bitmask. It efficiently reduces the problem size by leveraging bitwise operations to handle subsets. For more complex problems, combine it with other DP strategies (like transition between rows in grid problems).
If you provide the specific problem details (from the image), I can give a tailored solution!


作者声明:本文包含人工智能生成内容。