DSA · Competitive Programmer · Pattern 5 of 9
Advanced DP (Bitmask, Digit, Interval)
15 problems.
Your progress0%
- 1st Visit
- 0/15
- 2nd Visit
- 0/15
- Revise
- 0/15
About this pattern
Some DP states do not fit a simple index. Bitmask DP encodes a subset of up to about 20 items in an integer, as in dp[mask][last] for ordering or assignment problems, usually costing O(2^n * n^2). Digit DP counts numbers in a range [L, R] with a digit property by walking the digits of the bound with a tight flag and computing f(R) - f(L - 1). Interval DP solves dp[l][r] for a contiguous segment by choosing a split point or the element handled last, typically in O(n^3). Signals: n <= 20 for bitmasks, bounds up to 10^18 with a digit condition, or merging and deleting adjacent blocks for intervals.
// Bitmask DP over orderings: dp[mask][last], n <= 18 items
long long bestOrder(int n, const vector<vector<long long>>& gain) {
const long long NEG = LLONG_MIN / 4;
vector<vector<long long>> dp(1 << n, vector<long long>(n, NEG));
for (int i = 0; i < n; i++) dp[1 << i][i] = 0;
long long best = NEG;
for (int mask = 1; mask < (1 << n); mask++)
for (int last = 0; last < n; last++) {
if (dp[mask][last] == NEG) continue;
best = max(best, dp[mask][last]);
for (int nxt = 0; nxt < n; nxt++) {
if (mask >> nxt & 1) continue;
long long& to = dp[mask | 1 << nxt][nxt];
to = max(to, dp[mask][last] + gain[last][nxt]);
}
}
return best;
}