Not Frequent
0/20

Authors: Michael Cao, Siyong Huang

Contributors: Andrew Wang, Neo Wang

DP problems that require iterating over subsets.

### Pro Tip

You can often use this to solve subtasks.

Focus Problem – try your best to solve this problem before continuing!

### Tutorial

Resources
CPH

Elevator Rides, SOS, Hamiltonian

nwatx
PAPS

example - similar to Hamiltonian

CF

Hamiltonian walks

DPCC

Diagram

HE

### Solution

Let $dp[S][i]$ be the number of routes that visit all the cities in the subset $S$ and end at city $i$. The transitions will then be:

$dp[S][i] = \sum_{x \in adj[i]} dp[S \setminus \{i\}][x] \text{ if x \in S}$

where $S \setminus \{i\}$ is the subset $S$ without city $i$.

C++

#include <bits/stdc++.h>using namespace std;
using ll = long long;
const int MAX_N = 20;const ll MOD = (ll)1e9 + 7;
ll dp[1 << MAX_N][MAX_N];// come_from[i] contains the cities that can fly to i

### Problems

StatusSourceProblem NameDifficultyTags
ACEasy
CFEasy
Old GoldEasy
Old GoldEasy
GoldNormal
CSESNormal
IZhONormal
KattisNormal
Show TagsBinary Search, Bitmasks, DP, Geometry
YSHard
Show TagsBitmasks, DP, Meet in Middle
GoldHard
Show TagsBitwise, DP
IZhOHard
COCIHard
Show TagsBitmasks, DP, Game Theory, Tree
GoldHard
CEOIVery Hard
IOIVery Hard

## Application - Bitmask over Primes

### Rough Idea

In some number theory problems, it helps to represent each number with a bitmask of its prime divisors. For example, the set $\{6, 10, 15 \}$ can be represented by $\{0b011, 0b101, 0b110 \}$ (in binary), where the bits correspond to divisibility by $[2, 3, 5]$.

Then, here are some equivalent operations between masks and these integers:

• Bitwise AND is GCD
• Bitwise OR is LCM
• Iterating over bits is iterating over prime divisors
• Iterating over submasks is iterating over divisors

Choosing a set with GCD $1$ is equivalent to choosing a set of bitmasks that AND to $0$. For example, we can see that $\{6, 10 \}$ doesn't have GCD $1$ because $0b011 \& 0b101 = 0b001 \neq 0$. On the other hand, $\{6, 10, 15 \}$ has GCD $1$ because $0b011 \& 0b101 \& 0b110 = 0b000 = 0$.

### Problems

StatusSourceProblem NameDifficultyTags
CFHard
Show TagsCombinatorics, DP
CFVery Hard