This is not a textbook. This is your arsenal. Every template is contest-tested, every function is copy-paste ready, every pattern is mapped to the problem types that actually appear in ICPC and Codeforces Div 1/2. From the moment you open this file to the moment you submit AC — this is the only reference you need.
This is the file you paste at the start of every contest. Every macro, every typedef, every fast-I/O trick — pre-loaded and battle-tested. The goal: zero boilerplate overhead when the clock starts.
using ll = long long;: Prevents 90% of integer overflow bugs. When in doubt, use ll.#define pb push_back: Saves seconds typing adjacency lists and array builders, which compound over a contest.#define all(x) (x).begin(),(x).end(): Turns sort(v.begin(), v.end()) into sort(all(v)). Eliminates typo risks.#define sz(x) (int)(x).size(): size() yields an unsigned type, which breaks horribly when subtracting (e.g., v.size() - 1 becomes 4 billion if the vector is empty). This casts it to signed int.#define rep(i,a,b): Clean syntax for loops. Reduces loop index boundary errors (< vs <=).chmin/chmax: Turns dp[i] = min(dp[i], cost) into chmin(dp[i], cost), streamlining DP transitions visually and textually.Add -DLOCAL to your compile command: g++ -std=c++17 -O2 -DLOCAL -Wall sol.cpp -o sol. Then use dbg(variable) freely. On the online judge, -DLOCAL is not set, so all debug output is compiled away — no performance impact, no runtime errors.
Trigger: Any problem asking you to "output the answer modulo 10⁹+7" involving division (e.g., combinatorics nCr, probabilities P/Q mod M).
Constraints: MOD must be prime for Fermat's Little Theorem (inv(a) = a^(MOD-2)). If MOD is not prime, use Extended Euclidean.
Trap: Taking the inverse of 0 is undefined. Assure a and MOD are coprime.
If n or r > MOD (or MOD is a small prime), use Lucas: nCr(n,r) mod p = nCr(n/p, r/p) * nCr(n%p, r%p) mod p. Call recursively until base case. Essential for problems where n can be up to 10¹⁸ but MOD is a small prime.
Trigger: You need to prime factorize multiple queries (e.g., 10⁵ queries) of numbers up to 10⁷. Or you need to quickly compute Phi/Sigma for a range.
Constraints: N can be up to 10⁷ minimum. Array size hits 40MB for 10⁷ integers.
Trap: Don't use a sieve for N > 10⁸ (Memory Limit Exceeded). Use Pollard-Rho if you need to factorize sparse, large numbers (up to 10¹⁸).
Trigger: "Find the distance between u and v on a tree", "Path sum on a static tree", or queries requiring the k-th ancestor of a node.
Constraints: N, Q ≤ 2·10⁵. Precomputation takes O(N log N) memory and time. Queries are O(log N).
Trap: Array size for par[MAXV][LOG]. Ensure LOG is strictly > log2(MAXV). Also, don't swap u and v at the end of LCA if you need their original relative depth differences.
Trigger: Static array (NO updates) with 10⁶+ range queries for MIN, MAX, GCD, or Bitwise AND/OR.
Constraints: N ≤ 2·10⁵ (due to O(N log N) memory). Q can be up to 10⁷ since query is O(1).
Trap: The operation must be idempotent (f(x, x) = x). Do not use Sparse Table for Range Sum queries (use Prefix Sums or BIT instead).
Trigger: String matching ("find all occurrences of P in T"), finding the shortest repeating period of a string, or prefix-suffix overlaps.
Constraints: N + M ≤ 10⁶. Linear O(N) time and space.
Trap: When concatenating P + "#" + T, ensure the separator character # is absolutely not present in either string. Without it, the Z-array might exceed length(P) and give false positives.
Trigger: "Find the maximum bipartite matching", "Minimum number of cuts to separate A and B", "Assign items to buckets with capacities". If constraints allow V, E ≤ 10³, think Flow.
Constraints: In practice, Dinic's is insanely fast. It often crushes graphs with V=10⁴, E=10⁵ easily, especially on bipartite graphs (where it runs in O(E√V)).
Trap: Building the graph correctly is 99% of the problem. Don't forget to add reverse edges with 0 capacity for directed graphs. Remember that Min-Cut edges are those going from the BFS-reachable component to the non-reachable component in the residual graph.
Max flow = min cut (König's theorem). Bipartite matching = max flow with source/sink. Assignment problem = min-cost max-flow. Circulation problems = flow with lower bounds. If you see "maximum number of non-conflicting paths" or "minimum number of elements to remove to disconnect" — it's flow.
Digit DP counts numbers in a range satisfying a digit-based constraint (sum of digits = k, no consecutive equal digits, etc.) by processing digits one by one, tracking a state and a "tight" flag.
| Problem Pattern (what you read) | Algorithm (what you code) | Complexity |
|---|---|---|
| "Count numbers in [L,R] with property on digits" | Digit DP | O(D·S) |
| "Maximum flow / minimum cut between nodes" | Dinic's Algorithm | O(V²E) |
| "Minimum path/cut to disconnect graph" | Min-Cut = Max-Flow | O(V²E) |
| "Maximum matching in bipartite graph" | Hopcroft-Karp | O(E√V) |
| "k-th ancestor of node / LCA queries" | Binary Lifting | O(log N) |
| "Path sum / range update on tree path" | HLD + Segment Tree | O(log²N) |
| "Count paths of length k on tree" | Centroid Decomposition | O(N log N) |
| "Range min/max query (static array)" | Sparse Table | O(1) query |
| "Range update + range query (dynamic)" | Lazy Propagation SegTree | O(log N) |
| "Find all palindromes in string" | Manacher's O(n) | O(N) |
| "String matching / pattern in text" | KMP or Z-Algorithm | O(N+M) |
| "Compare substrings quickly" | Polynomial Hashing | O(1) per query |
| "Find bridges / articulation points" | Tarjan's DFS | O(V+E) |
| "Strongly connected components" | Tarjan's / Kosaraju's | O(V+E) |
| "Is there a way to order tasks? / Cycle?" | Topological Sort / Kahn's | O(V+E) |
| "Shortest path with negative edges" | Bellman-Ford | O(VE) |
| "All-pairs shortest paths, small V" | Floyd-Warshall | O(V³) |
| "Minimum spanning tree" | Kruskal + DSU | O(E log E) |
| "Count/sum of subset queries" | SOS DP (bitmask) | O(N·2ⁿ) |
| "Polynomial multiplication / counting" | NTT / FFT | O(N log N) |
| "Many range queries offline" | Mo's Algorithm | O((N+Q)√N) |
| "DP with lines y=mx+b optimization" | Convex Hull Trick / Li Chao | O(N) or O(N log N) |
| "Monotone optimal split in DP" | D&C Optimization / Knuth's | O(N log N) or O(N²) |
| "Game: who wins / Grundy values" | Sprague-Grundy, Nim | Problem-specific |
| "Permutation / symmetry counting" | Burnside + Pólya | O(|G|) |
| "Large n mod prime / choose" | Lucas' Theorem | O(p log n) |
Yes, you must solve the easy problems first to secure your rank. But the biggest trap is the whole team tunnel-visioning on a single tricky "easy" problem while abandoning the rest of the problem set. If a problem is rated "easy" but has an implementation trap or brutal edge cases, move on. Do not spend 90 minutes debugging Problem B while Problem E is actually a standard textbook algorithm you know completely. Keep reading, keep moving.
One person reads ALL problems simultaneously from front to back, catching the obvious templates. Classify each: Easy, Medium, Hard. Attack easiest first — getting points on the board early matters quickly. Set up environment.
Submit the guaranteed A/B/C tier problems. Any WA — print the code, jump off the PC, and debug on paper. PC time is gold. Never think for hours on a single problem if teammates are idle. Rotate if stuck.
This is where contests are won. One person defends already-solved problems (edge cases, WA fixes). One person attacks the next hardest unsolved. The third person validates ideas before coding — 30 minutes writing the wrong algorithm is fatal.
Freeze the scoreboard. Do not start new implementations from scratch unless it's 20 lines. Focus entirely on debugging the closest remaining problem. Write stress tests. Scrutinize constraints, variable overflows, and modulos.
Announce when you "think you have it" — teammate sanity-checks before you spend 45 minutes coding. Use the shared notebook. Agree on variable naming conventions beforehand.
Read the problem again from scratch — you often misread constraints. Check: is the answer always a specific structure? Can you brute force small cases and observe a pattern? Is there a simpler equivalent problem?
n≤10 → brute force. n≤20 → bitmask/meet-in-middle. n≤10³ → O(n²). n≤10⁵ → O(n log n). n≤10⁶ → O(n). n≤10¹⁸ → O(log n) or O(1). Let constraints tell you the algorithm.
ll for all intermediate products? Multiply two ints before casting?long double. Never compare with ==. Use fabsl(a-b) < EPS.| Rating | What to Master | Problems to Solve |
|---|---|---|
| Newbie → Pupil (800–1200) | Implementation, basic math, greedy, simple arrays/strings, brute force | Solve every A+B from Div3 contests |
| Pupil → Specialist (1200–1600) | Binary search, two pointers, prefix sums, basic DP, basic graphs (BFS/DFS) | 150+ problems rated 1200–1500 |
| Specialist → Expert (1600–1900) | Sorting with custom comparator, segment trees, DSU, Dijkstra, basic backtracking, divide and conquer | 200+ problems rated 1500–1800 |
| Expert → Candidate Master (1900–2100) | Advanced DP (bitmask, interval, D&C opt), flows, binary lifting, CHT, Sparse Table, HLD | File 05 + File 06 mastery + 300+ problems |
| Master+ (2100+) | Everything in this file + FFT/NTT, advanced geometry, research-level insights, speed | Thousands of problems + ICPC practice |
Knowing algorithms is 20%. Reading problems fast, not panicking under time pressure, clean bug-free code at speed — that's 80%. This file gives you the weapons. You build the instincts by solving problems, thousands of them, consistently. There is no shortcut. The ones who reach ICPC World Finals solve 2000+ problems before they get there. Start today.
CF: 1288C, 1204C, 1117C, 862B, 1284B. CSES: Array Division, Factory Machines, Subarray Distinct Values. Key: practice BS on answer space.
CF: 837D (DP+BIT), 1498E (digit DP), 436E (DP opt), 660F (bitmask). CSES: full DP section (15 problems). AtCoder DP Contest: all 26 problems.
CF: 1030E (LCA), 916E (centroid), 1239D (SCC+2-SAT), 962F (flow). CSES: full graph section. Must do: 2-SAT, SCC condensation problems.
CF: 1063F (suffix array), 1063G (hashing+BS), 126E (Manacher). CSES: string hashing section. Hackerrank: advanced strings.
CF: 600E (HLD), 916E (centroid decomp), 1017E (binary lifting+DP). CSES: full tree section (15 problems). Must do: tree diameter, tree DP.
ICPC World Finals problems (all years). Kattis: ICPC problem set. SPOJ: CLAS, QTREE series. POJ: classic ICPC-style problems. Solve old regionals.