Five dynamic programming problems rated 1,900 to 2,000 where the state is the hard part. The move: name the smallest summary of the past that the future needs, then count states and work per state.
This tent holds five dynamic programming problems rated 1,900 to 2,000. You can write each recurrence in a line once you know the state. The difficulty is finding a state that is small enough, and then making each step cheap.
The camp before this one, Dynamic programming for contests, changed the table. Here the state itself is new.
| Problem | The state | Its size at the limits |
|---|---|---|
| Valid orders for the steps of a release | the set of steps already placed | 2^18 = 262,144 states instead of 6,402,373,705,728,000 orders |
| Product codes with a lucky digit sum | the digits placed so far, with a flag | 13,500 steps instead of 10^14 numbers |
| Homepage categories that hang together | the best profit for each size, per subtree | 9 × 10^6 steps instead of 2.7 × 10^10 |
| Expected requests until the daily goal | the expected count from each total | 10^5 states, each a window sum |
| Ad breaks with a minimum and a maximum gap | the best plan ending at each slot | 2 × 10^5 queue steps instead of 10^10 |
Exercise · Predict the output: Orders with before-and-after rules. Four steps are numbered 0 to 3. Step 2 must come after step 0 and after step 1. The array dp[mask] counts the orders that place exactly the steps in the mask. What does this print: dp for all four steps, then dp for the steps 0 and 1?
n = 4
needs = [[0, 2], [1, 2]]
dp = [0] * 16
dp[0] = 1
for mask in range(16):
for i in range(n):
if mask >> i & 1:
continue
ok = True
for a, b in needs:
if b == i and not (mask >> a & 1):
ok = False
if ok:
dp[mask | 1 << i] += dp[mask]
print(dp[15], dp[3])A state is what the future of the problem needs to know about the past, and nothing more. Two different pasts with the same summary must have the same future. That is why a dp can merge them into one cell.
Name the smallest summary of the past that the future needs. Count the states and the work per state against the limits, and only then write the recurrence.
The summary differs in each problem. For the release steps it is the set already placed: the order inside the set no longer matters, only which steps are done. For the numbers it is the digit sum so far and whether the prefix still equals the limit. For a tree it is the best profit for each count of chosen categories.
Each problem adds one trick on top. With bit masks, the masks must be processed in increasing order, because a mask is built from smaller masks. With digits, count from 0 up to a limit, and subtract two such counts for a range.
A mask dp builds each mask from smaller masks, so the masks are walked upwards; the state is the set of steps already placed.
Exercise · Find the bug: The mask that is used too early. This counts the orders of n steps. A mask's count is built from smaller masks. Which line is wrong?
def count_orders(n):
full = (1 << n) - 1
dp = [0] * (full + 1)
dp[0] = 1
for mask in range(full, -1, -1):
for i in range(n):
if not (mask >> i & 1):
dp[mask | 1 << i] += dp[mask]
return dp[full]The Academy lessons DP from recursion, Knapsack and Interval DP gave you states made of one or two numbers. Monotonic deque and Tree recursion gave you the tools for the last two problems. This tent uses states that are sets, flags and tables.
Three new habits show up. A set becomes a bit mask. A range of numbers becomes a difference of two prefix counts. And a merge over a tree is bounded by the sizes of the subtrees, so that the total work stays near n × k and not n × k².
The prefix count is the easy place to slip. The count over [low, high] is f(high) - f(low - 1). It is tempting to write f(low), which loses the number low whenever it meets the rule.
A range count is f of high minus f of low minus one; subtracting f of low removes the number low itself.
Exercise · Break it: The range that loses its first number. This counts the integers from low to high, both included, whose digits add up to a multiple of k. It counts from 0 up to a limit and subtracts f(low) from f(high). Find an input where it is wrong.
def count_codes(low, high, k):
def count_up_to(limit):
digits = [int(c) for c in str(limit)]
free = [0] * k
tight = 0
for d in digits:
nxt = [0] * k
for s in range(k):
for dig in range(10):
nxt[(s + dig) % k] += free[s]
for dig in range(d):
nxt[(tight + dig) % k] += 1
tight = (tight + d) % k
free = nxt
return free[0] + (1 if tight == 0 else 0)
return count_up_to(high) - count_up_to(low)| Limit | What it tells you |
|---|---|
| at most 18 items | a dp over 2^18 = 262,144 masks: the state is a set |
| numbers up to 10^14, k up to 90 | 15 digits × 90 sums × 10 digits: the state is a digit and a sum |
| 3,000 categories, k up to 3,000 | tables capped at k: about 9 × 10^6 merge steps |
| goal up to 10^5, a prime modulus | a fraction needs an inverse: work modulo 998,244,353 |
| windows up to 10^5 slots | a deque: every slot enters and leaves once |
The full treatment is in Fast I/O and stress testing. The input here is a count of steps, then the rules as pairs of steps numbered from 1. A mask dp needs a 64-bit array, because the count of orders reaches 18! at the limit.
import sys
def main():
data = sys.stdin.buffer.read().split()
n, m = int(data[0]), int(data[1])
before = [0] * n
for j in range(m):
a, b = int(data[2 + 2 * j]) - 1, int(data[3 + 2 * j]) - 1
before[b] |= 1 << a
full = (1 << n) - 1
dp = [0] * (full + 1)
dp[0] = 1
for mask in range(full + 1):
if dp[mask] == 0:
continue
for i in range(n):
if not (mask >> i & 1) and (before[i] & mask) == before[i]:
dp[mask | 1 << i] += dp[mask]
sys.stdout.write(str(dp[full]) + "\n")
main()import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
in.nextToken();
int n = (int) in.nval;
in.nextToken();
int m = (int) in.nval;
int[] before = new int[n];
for (int j = 0; j < m; j++) {
in.nextToken();
int a = (int) in.nval - 1;
in.nextToken();
int b = (int) in.nval - 1;
before[b] |= 1 << a;
}
int full = (1 << n) - 1;
long[] dp = new long[full + 1];
dp[0] = 1;
for (int mask = 0; mask <= full; mask++) {
if (dp[mask] == 0) continue;
for (int i = 0; i < n; i++) {
if ((mask >> i & 1) == 0 && (before[i] & mask) == before[i]) dp[mask | 1 << i] += dp[mask];
}
}
System.out.println(dp[full]);
}
}#include <iostream>
#include <vector>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, m;
cin >> n >> m;
vector<int> before(n, 0);
for (int j = 0; j < m; j++) {
int a, b;
cin >> a >> b;
before[b - 1] |= 1 << (a - 1);
}
int full = (1 << n) - 1;
vector<long long> dp(full + 1, 0);
dp[0] = 1;
for (int mask = 0; mask <= full; mask++) {
if (dp[mask] == 0) continue;
for (int i = 0; i < n; i++) {
if ((mask >> i & 1) == 0 && (before[i] & mask) == before[i]) dp[mask | 1 << i] += dp[mask];
}
}
cout << dp[full] << "\n";
}const data = require("fs").readFileSync(0, "utf8").split(/\s+/).filter(Boolean).map(Number);
const n = data[0], m = data[1];
const before = new Array(n).fill(0);
for (let j = 0; j < m; j++) {
const a = data[2 + 2 * j] - 1, b = data[3 + 2 * j] - 1;
before[b] |= 1 << a;
}
const full = (1 << n) - 1;
const dp = new Array(full + 1).fill(0);
dp[0] = 1;
for (let mask = 0; mask <= full; mask++) {
if (dp[mask] === 0) continue;
for (let i = 0; i < n; i++) {
if ((mask >> i & 1) === 0 && (before[i] & mask) === before[i]) dp[mask | 1 << i] += dp[mask];
}
}
process.stdout.write(String(dp[full]) + "\n");On the sample 4 2 with the rules 1 3 and 2 3, all four programs print 8. For n = 18 with no rules the count is 18! = 6,402,373,705,728,000. That is below 2^63 but far above 2^53, so JavaScript would need a big integer there.
The slow twin tries every order of the steps and checks each rule. It is only safe for up to 6 steps, which is all the stress test needs.
import itertools
import random
from fast import count_orders
from slow import count_orders as slow_orders
for seed in range(1000):
rng = random.Random(seed)
n = rng.randint(1, 6)
needs = []
if n > 1:
for _ in range(rng.randint(0, 4)):
needs.append(rng.sample(range(n), 2))
if count_orders(n, needs) != slow_orders(n, needs):
print("different at", n, needs)
break
else:
print("all 1000 inputs agree")The run prints all 1000 inputs agree. Walk the masks downwards and seed 0 fails. For 4 steps and the rules 0 before 1, 3 before 1 and 2 before 1, it gives 0 instead of 6.
At 1,800 to 2,000 the state is the work. Write the state, its size and the work per state in one line before you code. Aim for about 45 minutes a problem, and keep 10 for the stress test on tiny inputs.
The first two have states that are a set and a digit prefix. The last three, rated 2,000, add a bounded merge on a tree, an expectation as a fraction, and a deque over a window.
For each problem, write the state, its size and the work per state in one line. Then write the slow twin that tries every possibility on tiny inputs, and stress test.
Checkpoint · Advanced dp
Q1/5 What does a good dp state contain?
Answer: B
Two different pasts with the same summary have the same future, so a dp merges them into one cell. For the release steps the summary is the set already placed.
Q2/5 How many states does a dp over the subsets of 18 items have, and how many orders does it replace?
Answer: B
There are 2^18 = 262,144 masks. The orders of 18 items are 18!, which a mask dp never lists.
Q3/5 Why must a mask dp process the masks in increasing order?
Answer: B
Going downwards, dp[3] is used while dp[1] and dp[2] are still 0, so n = 2 returns 0 instead of 2.
Q4/5 How many integers from 3 to 10 have a digit sum that is a multiple of 3?
Answer: B
The numbers 3, 6 and 9 qualify. f(10) - f(3) finds 2, because f(3) includes the number 3 itself. The range needs f(10) - f(2).
Q5/5 What does a rating of 1,800 to 2,000 usually ask of you?
Answer: B
The recurrences are short once the state is right. The work is the state, its size, and the trick on top.
Review cards from this lesson.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.