Last active
June 28, 2026 17:40
-
-
Save jcoding09/1880f5b6999f61dd3221ba4785713733 to your computer and use it in GitHub Desktop.
- 1-D DP β Linear state problems (Fibonacci, House Robber, Climbing Stairs)
- Hard Problems on 1-D DP β Advanced single-dimension state transitions
- 2-D DP β Grid/matrix problems, two-variable states
- 3-D / 4-D DP β Multi-dimensional state spaces
- Subarray / Mix DP β DP on subarrays (MCM, Burst Balloons)
- Partition DP β Splitting arrays/strings optimally
- Partition DP + Optimization β With divide & conquer or other speedups
- Digit DP β Counting numbers with digit constraints (along with optimization)
- Knapsack DP β 0/1, Unbounded, Bounded knapsack
- Knapsack DP + Variations & Optimizations β Subset sum, target sum variants
- String DP β LCS, Edit Distance, and all variations
- Special Optimizations on DP β Hashing / Math / Convex-Hull Trick / Observations / Segment Tree / Stack Optimization
- LIS DP β Longest Increasing Subsequence and variants (LDS, LIDS, etc.)
- Miscellaneous DP β Problems that don't fit neatly elsewhere
- Kadane DP β Prefix / Suffix / Hashing + DP hybrids
- Tiling DP + Broken DP β Domino tiling, broken tile problems
- Bitmask DP β State compression using bitmasks (TSP, assignment problems)
- Tree DP β DP on trees (rerooting technique, subtree states)
- DP on Graphs / DAG DP β Longest path in DAG, topological order DP
- Interval DP β Palindrome partitioning, matrix chain, optimal BST
- Probability / Expected Value DP β Games, dice, random walks
- DP + Data Structures β BIT/Fenwick, Segment Tree augmented DP
- SOS DP (Sum over Subsets) β Subset enumeration with bitmask
- Profile DP β Row-by-row state compression (broken profile)
- DP on Strings with Automata β Aho-Corasick + DP, regex matching
| Level | Categories |
|---|---|
| Beginner | 1-D DP, 2-D DP, Knapsack, String DP |
| Intermediate | Partition DP, LIS, Interval DP, Tree DP, Bitmask DP |
| Advanced | Digit DP, SOS DP, Profile DP, Convex Hull Trick, Automata DP |
| Expert | 3-D/4-D DP, Stack Optimization, DP + Segment Tree, Probability DP |
-
1-D DP
- Linear state problems (Fibonacci, House Robber, Climbing Stairs)
-
2-D DP
- Grid/matrix problems, two-variable states
-
Knapsack DP
- 0/1, Unbounded, Bounded knapsack
-
String DP
- LCS, Edit Distance, and all variations
-
LIS DP
- Longest Increasing Subsequence and variants (LDS, LIDS)
-
Kadane DP
- Prefix / Suffix / Hashing + DP hybrids
-
Hard Problems on 1-D DP
- Advanced single-dimension state transitions
-
Subarray / Mix DP
- DP on subarrays (MCM, Burst Balloons)
-
Partition DP
- Splitting arrays/strings optimally
-
Knapsack DP + Variations & Optimizations
- Subset sum, target sum variants
-
Interval DP
- Palindrome partitioning, matrix chain, optimal BST
-
Tiling DP + Broken DP
- Domino tiling, broken tile problems
-
Tree DP
- DP on trees (rerooting technique, subtree states)
-
Miscellaneous DP
- Problems that don't fit neatly elsewhere
-
3-D / 4-D DP
- Multi-dimensional state spaces
-
Partition DP + Optimization
- With divide & conquer or other speedups
-
Digit DP
- Counting numbers with digit constraints (along with optimization)
-
Bitmask DP
- State compression using bitmasks (TSP, assignment problems)
-
DP on Graphs / DAG DP
- Longest path in DAG, topological order DP
-
Probability / Expected Value DP
- Games, dice, random walks
-
SOS DP (Sum over Subsets)
- Subset enumeration with bitmask
-
Special Optimizations on DP
- Hashing / Math / Convex-Hull Trick / Observations / Segment Tree / Stack Optimization
-
DP + Data Structures
- BIT/Fenwick, Segment Tree augmented DP
-
Profile DP
- Row-by-row state compression (broken profile)
-
DP on Strings with Automata
- Aho-Corasick + DP, regex matching
- I/O:
cin/cout, fast I/O:
ios_base::sync_with_stdio(false);
cin.tie(NULL);- Use
\ninstead ofendl(avoids buffer flush) - Control Flow:
if/else/switch,for/while/do-while, range-based loops - Functions: Pass-by-value vs pass-by-reference (
&), global vs local scope
- Types:
int,long long,float,double,char,string,bool,__int128 - Bounds:
intβ Β±2Γ10βΉ |long longβ Β±9Γ10ΒΉβΈ - Overflow fix:
1LL * a * b - Modulo rules:
(A+B)%M = ((A%M)+(B%M))%M(AΓB)%M = ((A%M)Γ(B%M))%M(A-B)%M = ((A%M)-(B%M)+M)%M
- Big O / Ξ© / Ξ β worst, best, average cases
- Golden Rule: ~10βΈ ops/sec on judge
| Constraint | Expected Complexity |
|---|---|
| N β€ 10 | O(N!) or O(2^N Β· NΒ²) |
| N β€ 20 | O(2^N) |
| N β€ 500 | O(NΒ³) |
| N β€ 5000 | O(NΒ²) |
| N β€ 2Γ10β΅ | O(N log N) |
| N β€ 10β· | O(N) |
| Large N | O(log N) or O(1) |
- Space: 256β512MB typical limit | int array of 10β· β 40MB
- Containers:
vector,pair,tuple - Iterators:
begin/end,rbegin/rend - Algorithms:
sort,reverse,max_element,min_element
- 1D/2D arrays, cache efficiency, contiguous memory
- Grid traversal (4-directional / 8-directional)
substr(),find(),stringstream,to_string(),stoi()chararrays vsstd::stringβ null terminators, layout
- 1D prefix sum β O(1) range queries
- 2D prefix sum β O(1) submatrix queries
- Difference array β O(1) range updates + single prefix reconstruct
- Coordinate compression β map sparse values to dense indices
- Converging (pair sum, palindrome check)
- Independent (merge sorted arrays, fast/slow pointer)
- Fixed size β rolling max/sum of size K
- Variable size β longest subarray satisfying constraint
- Merge Sort / Quick Sort internals (Divide & Conquer)
- Custom comparators, lambda sort, operator
<overloading - Strict Weak Ordering rules
lower_bound(β₯ target),upper_bound(> target),binary_search- Binary Search on Answer β monotonic predicate (T...T F...F)
- Floating point BS: use 100 fixed iterations
| Operation | Code |
|---|---|
| Check bit i | mask & (1 << i) |
| Set bit i | mask | (1 << i) |
| Clear bit i | mask & ~(1 << i) |
| Toggle bit i | mask ^ (1 << i) |
| Lowest set bit | mask & (-mask) |
- GCC builtins:
__builtin_popcount,__builtin_clz,__builtin_ctz - Bitmasks for subset representation (N β€ 30)
- Locally optimal β globally optimal
- Activity selection, Fractional Knapsack, Huffman Coding
- Proof: Exchange argument / Staying ahead
- Sieve of Eratosthenes β all primes up to N in O(N log log N)
- GCD / LCM β
__gcd(), Euclidean algorithm - Modular Exponentiation β fast power in O(log N)
long long power(long long base, long long exp, long long mod) {
long long result = 1;
while (exp > 0) {
if (exp & 1) result = result * base % mod;
base = base * base % mod;
exp >>= 1;
}
return result;
}- Modular Inverse β Fermat's little theorem:
a^(M-2) % M(M prime) - Prime Factorization β trial division, smallest prime factor sieve
- Euler's Totient Function Ο(N)
- Chinese Remainder Theorem (CRT) β basic application
- Base cases, call stack depth, recurrence relations
- Execution tree visualization, stack overflow awareness
- Stack (
std::stack): Balanced parentheses, expression parsing - Monotonic Stack: NGE / PSE queries in O(N)
- Queue (
std::queue): BFS backbone, FIFO - Deque (
std::deque): O(1) push/pop both ends β Sliding window max
set / map / multisetβ O(log N), Red-Black tree backedunordered_map / unordered_setβ O(1) avg,β οΈ anti-hash vulnerable- Fix with custom hash:
struct custom_hash {
static uint64_t splitmix64(uint64_t x) {
x += 0x9e3779b97f4a7c15;
x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;
x = (x ^ (x >> 27)) * 0x94d049bb133111eb;
return x ^ (x >> 31);
}
size_t operator()(uint64_t x) const {
static const uint64_t FIXED_RANDOM =
chrono::steady_clock::now().time_since_epoch().count();
return splitmix64(x + FIXED_RANDOM);
}
};
// unordered_map<long long, int, custom_hash> safe_map;- Generate subsets, permutations, power set
- N-Queens, Sudoku Solver
- Prune dead-end branches early
(New dedicated tier β critical before advanced DP)
- Point update + prefix sum query in O(log N)
- 2D BIT for matrix range queries
- Applications: Inversion count, order statistics
- Range query + point update in O(log N)
- Lazy Propagation β range update + range query in O(log N)
- Applications: Range min/max/sum, range assignment
- Merge sort tree variant for frequency queries
- O(1) range min/max queries (static arrays, no updates)
- Build in O(N log N), query in O(1) β ideal for RMQ
find()with path compressionunion()with union by rank/size- O(Ξ±(N)) β O(1) amortized per operation
- Applications: Connected components, Kruskal's MST, cycle detection
- Adjacency Matrix β O(1) lookup, O(VΒ²) space
- Adjacency List β O(V+E) space (always prefer this)
- Edge List β for MST algorithms
- Shortest path in unweighted graphs, connected components
- Bipartite graph detection
- 0-1 BFS β deque, weights β {0,1}, O(V+E)
- Cycle detection (directed + undirected)
- Connected components, Flood Fill
- Euler Tour β entry/exit timestamps for subtree queries
| Algorithm | Weights | Complexity | Use Case |
|---|---|---|---|
| BFS | Unweighted | O(V+E) | Equal edge weights |
| Dijkstra | Non-negative | O((V+E) log V) | Standard SSSP |
| Bellman-Ford | Any (neg OK) | O(VΓE) | Negative edges |
| Floyd-Warshall | Any | O(VΒ³) | All pairs SP |
| 0-1 BFS | {0,1} only | O(V+E) | Binary weights |
- Kahn's Algorithm (BFS) β in-degree tracking
- DFS-based β post-order reversal
- Applications: Task scheduling, DAG DP ordering
- Kruskal's β sort edges + DSU, O(E log E)
- Prim's β priority queue, O((V+E) log V)
- Connected acyclic graph, exactly V-1 edges
- Pre/In/Post-order traversals
- DFS: depth, height, subtree sizes
- Tree Diameter β 2Γ DFS or DP
- LCA (Lowest Common Ancestor) β binary lifting, O(N log N) build, O(log N) query
- Inversion count via Merge Sort
- Closest pair of points
- Prerequisites: Overlapping subproblems + Optimal substructure
- Top-Down: Recursion + memoization (cache array)
- Bottom-Up: Iterative tabulation, no recursion overhead
- Always define: State β Transition β Base Case
- Fibonacci variants, climbing stairs
- House Robber (non-adjacent selection)
- Max subarray (Kadane's Algorithm)
- Jump Game variants
- Grid path counting with obstacles
- Minimum path sum in grid
- Unique paths with constraints
- 0/1 Knapsack β take or leave, no reuse
- Unbounded Knapsack β infinite item reuse
- Bounded Knapsack β limited item count
- Subset Sum β exact target reachability
- Partition DP β equal subset split
- LCS β Longest Common Subsequence (2D table)
- Edit Distance β insert / delete / replace
- LPS β Longest Palindromic Subsequence
- Wildcard / Regex Matching
- Distinct Subsequences
- Standard LIS β O(NΒ²)
- Optimized LIS β O(N log N) with
lower_bound - Variants: LDS, LIDS, LIS count, print LIS
- Russian Doll Envelopes (2D LIS)
- Matrix Chain Multiplication
- Burst Balloons
- Palindrome Partitioning
- Optimal BST
- Template:
for length 2 β N:
for every interval [i, j] of that length:
for every split point k in [i, j]:
dp[i][j] = optimal(dp[i][k] + dp[k+1][j] + cost)- Rod Cutting
- Palindrome min-cut partitioning
- Egg Drop Problem
- Splitting array into K parts optimally
- Count numbers in [L, R] satisfying digit constraints
- States:
(index, tight, started, criteria) - Applications: Count numbers with digit sum = K, no consecutive same digits
- Subsets as DP states (N β€ 20)
- TSP β O(2^N Β· NΒ²)
- Assignment Problem
- SOS DP (Sum over Subsets) β O(N Β· 2^N)
for (int mask = 0; mask < (1 << n); mask++)
for (int i = 0; i < n; i++)
if (mask & (1 << i))
dp[mask] += dp[mask ^ (1 << i)];dp[u][state]β subtree subproblems- Max Independent Set on Tree
- Subtree weight optimization
- Tree Diameter via DP
- Rerooting Technique β O(N) all-root DP
- Maximum subarray sum (Kadane's)
- Maximum subarray product
- Prefix + Suffix combination problems
- Hashing + DP hybrids
- Multiple simultaneous constraints
- Cherry Pickup (two paths simultaneously)
- DP with 3+ state variables
- Convex Hull Trick (CHT) β O(N) line optimization
- Li Chao Tree β dynamic CHT with arbitrary queries
- Divide & Conquer DP β opt monotonicity β O(N log N)
- Knuth's Optimization β interval DP β O(NΒ²) from O(NΒ³)
- Stack Optimization β monotonic stack on DP transitions
- Segment Tree / BIT on DP β range optimal transitions
- Profile DP β broken profile, row-by-row state compression
- Tiling DP + Broken DP β domino/tromino tiling
- Probability / Expected Value DP β games, dice, random walks
- DP on DAG β longest/shortest path via topological order
- LIS DP on Strings with Automata β Aho-Corasick + DP
- Rolling array β reduce NΓW to 2ΓW or 1ΓW
- Only store previous row/layer when current depends on it
- Recognize traversal direction matters (forward vs reverse)
| Difficulty | Categories |
|---|---|
| π’ Easy | 1-D DP, 2-D DP, Kadane, Basic Knapsack, Basic String DP |
| π‘ Medium | LIS, Full Knapsack, Full String DP, Partition DP, Tree DP basics |
| π΄ Hard | Interval DP, Digit DP, Bitmask DP, 3D/4D DP, Rerooting |
| β« Very Hard | CHT, Li Chao, D&C DP, Knuth's Opt, Profile DP, Automata DP |
| Tier | Target Problems | Goal |
|---|---|---|
| Tier 1β2 | 30β50 | Build speed & fluency |
| Tier 3β4 | 50β80 | Pattern recognition |
| Tier 5β6 | 60β100 | Graph confidence |
| Tier 7 DP | 100β150 | Master all DP types |
| Total | ~300 | Div.2 D/E ready |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <bits/stdc++.h> | |
| using namespace std; | |
| // βββββ Type Aliases βββββ | |
| // Rule of thumb: only alias a type if ALL 3 are true: | |
| // 1. You use it in >30% of problems | |
| // 2. You use it without modification (no custom comparator/hash/size) | |
| // 3. The original name is long enough to be annoying | |
| // e.g. vector<vector<int>> β all three β β aliased as vvi | |
| // vector<vector<vector<int>>> β fails rule 1 & 2 β skipped | |
| using ll = long long; | |
| using ull = unsigned long long; | |
| using ld = long double; | |
| using pii = pair<int, int>; | |
| using pll = pair<ll, ll>; | |
| using vi = vector<int>; | |
| using vll = vector<ll>; | |
| using vvi = vector<vector<int>>; | |
| using vvl = vector<vector<ll>>; | |
| using vpii = vector<pii>; | |
| using vpll = vector<pll>; | |
| using si = set<int>; | |
| using mii = map<int, int>; | |
| using mll = map<ll, ll>; | |
| using msi = map<string, int>; | |
| using str = string; | |
| // βββββ Macros βββββ | |
| #define all(x) (x).begin(), (x).end() | |
| #define rall(x) (x).rbegin(), (x).rend() | |
| #define pb push_back | |
| #define eb emplace_back | |
| #define fi first | |
| #define se second | |
| #define sz(x) (int)(x).size() | |
| #define rep(i, a, b) for (int i = (a); i < (b); ++i) | |
| #define per(i, a, b) for (int i = (b) - 1; i >= (a); --i) | |
| // βββββ Constants βββββ | |
| const int INF = 0x3f3f3f3f; | |
| const ll LINF = 0x3f3f3f3f3f3f3f3fLL; | |
| const int MOD = 1e9 + 7; | |
| const double PI = acos(-1.0); | |
| // βββββ Debug (disabled on judge) βββββ | |
| #ifdef LOCAL | |
| #define dbg(x) cerr << #x << " = " << (x) << "\n" | |
| #else | |
| #define dbg(x) | |
| #endif | |
| // βββββ Fast I/O βββββ | |
| void setIO(const string& name = "") { | |
| ios::sync_with_stdio(false); | |
| cin.tie(nullptr); | |
| if (!name.empty()) { | |
| freopen((name + ".in").c_str(), "r", stdin); | |
| freopen((name + ".out").c_str(), "w", stdout); | |
| } | |
| } | |
| // βββββ Utility βββββ | |
| template<typename T> void chmin(T& a, const T& b) { if (b < a) a = b; } | |
| template<typename T> void chmax(T& a, const T& b) { if (b > a) a = b; } | |
| ll power(ll base, ll exp, ll mod = MOD) { | |
| ll result = 1; | |
| base %= mod; | |
| while (exp > 0) { | |
| if (exp & 1) result = result * base % mod; | |
| base = base * base % mod; | |
| exp >>= 1; | |
| } | |
| return result; | |
| } | |
| // βββββββββββββββββββββββββββββββββββββββ | |
| void solve() { | |
| // ββ your solution here ββ | |
| } | |
| // βββββββββββββββββββββββββββββββββββββββ | |
| int main() { | |
| setIO(); // pass a filename string for file I/O, e.g. setIO("problem") | |
| int t = 1; | |
| cin >> t; // remove this line if there's only one test case | |
| while (t--) solve(); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment