All templates live in whoashish115/cp-template — every file is one complete, submittable C++20 program (dependencies pasted in, empty solve(), main()). Pick the file, write solve(), submit.

  • Usage, complexity and pitfalls of every file: NOTES.md
  • Blank base template: main.cpp
  • ICPC team notebook (25 pages): notebook/
  • Bundled libraries: AtCoder Library, KACTL
  • Every template compiles cleanly with g++ -std=c++20 -Wall (434/434 checked).

Which template?

Problem looks likeFile
range sum / point updaterange-queries/fenwick.cpp, segment-tree.cpp
range update + range query (add, assign, min, sum)range-queries/lazy-segment-tree.cpp (iterative: -iterative)
static range min / gcd, O(1) queryrange-queries/sparse-table.cpp, disjoint-sparse-table.cpp, linear-rmq.cpp
chmin / chmax on rangesrange-queries/segment-tree-beats.cpp
k-th smallest in range, count < x in rangerange-queries/wavelet-matrix.cpp, merge-sort-tree.cpp, persistent-segment-tree.cpp
distinct values in range, offline queriesrange-queries/distinct-in-range.cpp, mo.cpp, mo-with-updates.cpp, mo-rollback.cpp
2D sums / rectanglesrange-queries/fenwick-2d.cpp, segment-tree-2d.cpp, basics/prefix-sums.cpp, geometry/rectangle-union.cpp
connectivity / merging setsdata-structures/dsu.cpp, dsu-rollback.cpp, offline-dynamic-connectivity.cpp, weighted-dsu.cpp
ordered set with k-th / rankdata-structures/ordered-set.cpp (pbds), treap.cpp, avl-tree.cpp
array with insert / reverse / splitdata-structures/treap.cpp (implicit), splay-tree.cpp, pbds-heap-rope.cpp
interval assign (“Chtholly”)data-structures/interval-set.cpp
max xor pair / subset xordata-structures/binary-trie.cpp, linear-algebra/xor-basis.cpp
shortest pathgraphs/bfs.cpp (0-1 BFS too), dijkstra.cpp, bellman-ford.cpp, spfa.cpp, floyd-warshall.cpp, johnson.cpp
MSTgraphs/kruskal.cpp, prim.cpp, boruvka.cpp, directed-mst.cpp, geometry/manhattan-mst.cpp
SCC / 2-SAT / bridges / articulationgraphs/scc.cpp, two-sat.cpp, bridges-articulation.cpp, biconnected-components.cpp
Euler path, cycle finding, toposortgraphs/euler-path.cpp, find-cycle.cpp, topological-sort.cpp
matching / flow / assignmentflows/hopcroft-karp.cpp, dinic.cpp, min-cost-flow.cpp, hungarian.cpp, general-matching.cpp
min cut / project selectionflows/dinic.cpp (cut), max-closure.cpp, global-min-cut.cpp, gomory-hu.cpp
LCA, k-th ancestor, path queriestrees/lca-binary-lifting.cpp, lca-rmq.cpp, hld.cpp, ladder-kth-ancestor.cpp
subtree queries, small-to-largetrees/dsu-on-tree.cpp, rerooting.cpp, tree-knapsack.cpp, virtual-tree.cpp
paths of given length / distances in treetrees/centroid-decomposition.cpp, distance-counting.cpp, centroid-queries.cpp
dynamic tree (link / cut)trees/link-cut-tree.cpp, euler-tour-tree.cpp, top-tree.cpp
LIS / LCS / edit distance / knapsackdp/lis.cpp, lcs.cpp, edit-distance.cpp, knapsack.cpp, classic-dp.cpp
DP speedupsdp/convex-hull-trick.cpp, li-chao-tree.cpp, divide-and-conquer-dp.cpp, knuth-optimization.cpp, aliens-trick.cpp, slope-trick.cpp, monotone-1d1d.cpp
digits / bitmask / profile DPdp/digit-dp.cpp, tsp.cpp, sos-dp.cpp, broken-profile-dp.cpp, plug-dp.cpp
pattern matchingstrings/prefix-function.cpp, z-function.cpp, string-hashing.cpp, aho-corasick.cpp, wildcard-matching.cpp
substrings / suffixesstrings/suffix-array.cpp, suffix-automaton.cpp, suffix-tree.cpp
palindromesstrings/manacher.cpp, palindromic-tree.cpp, palindrome-factorization.cpp
primes, divisors, phi, mobiusnumber-theory/sieve.cpp, factorization.cpp, basic-number-theory.cpp, segmented-sieve.cpp
sums over floor(n / i), prime sumsnumber-theory/quotient-blocks.cpp, du-sieve.cpp, min25-sieve.cpp, prime-counting.cpp
modular equationsnumber-theory/crt.cpp, extended-gcd.cpp, discrete-log.cpp, mod-sqrt.cpp, primitive-root.cpp
nCr mod p / any m, Lucas, Catalancombinatorics/binomial.cpp, lucas.cpp, binomial-any-mod.cpp
counting with symmetry / partitionscombinatorics/burnside-lgv.cpp, stirling-bell-partitions.cpp, polynomial/counting-series.cpp
convolution / polynomialspolynomial/ntt.cpp, fft.cpp (any mod), poly.cpp (inv, log, exp, sqrt, eval)
linear recurrence, k-th termpolynomial/linear-recurrence.cpp, bostan-mori.cpp, berlekamp-massey.cpp, linear-algebra/matrix.cpp
xor / and / or convolutionpolynomial/bitwise-convolution.cpp, fwht-any-base.cpp
linear systems, determinant, ranklinear-algebra/gaussian-elimination.cpp, determinant.cpp, gauss-xor.cpp, matrix-tree.cpp
LPlinear-algebra/simplex.cpp
gamesgame-theory/sprague-grundy.cpp, retrograde.cpp, hackenbush.cpp, game-search.cpp
geometrygeometry/point.cpp, lines-segments.cpp, polygon.cpp, convex-hull.cpp, circle.cpp, half-plane-intersection.cpp
successor / functional graph, k-th successor, cyclesgraphs/functional-graph.cpp
grid BFS, flood fill, path letters, 0-1 BFS on gridgraphs/grid.cpp
path / subtree add + sum / max on a tree (one file)trees/hld-path-queries.cpp
second-best MST, MST forced to use an edgegraphs/second-best-mst.cpp
max / min xor walk between verticesgraphs/xor-paths.cpp
which sums of coins are representable (huge H)graphs/residue-shortest-path.cpp
is this degree sequence a graph / bipartite / tournamentgraphs/degree-sequence.cpp
DAG path cover, max antichain (Dilworth)flows/path-cover.cpp
exact cover, Sudoku, tilingsbasics/dancing-links.cpp, backtracking-puzzles.cpp
subsequence checks / distinct subsequencesstrings/subsequence-automaton.cpp
lattice paths with obstacles / reflectionscombinatorics/lattice-paths.cpp, special-numbers.cpp
f(g(x)), series reversionpolynomial/poly-composition.cpp
shortest walk with exactly k edgeslinear-algebra/min-plus-matrix.cpp
historic max, lines rising over timerange-queries/segment-tree-history.cpp, kinetic-segment-tree.cpp
compare multisets of subarrays, “is a permutation”misc/set-hashing.cpp
modulus above 2^31number-theory/modint64.cpp, fast-mod.cpp
more geometrygeometry/polygon-union.cpp, circle-union.cpp, delaunay.cpp, kd-tree.cpp, angular-sweep.cpp, segment-in-polygon.cpp, convex-distance.cpp, planar-faces.cpp, circle-inversion.cpp
interactivecontest/interactive.cpp (+ basics/binary-search.cpp)
huge numbers / fractions / datesmisc/bigint.cpp, fraction.cpp, dates.cpp, contest/int128-io.cpp
exact i64 convolution, convolution mod 1e9+7 / any mpolynomial/ntt.cpp (convolutionLL, convolutionAnyMod)
gcd / lcm convolutiondp/divisor-transforms.cpp
min / max of (a x + b) mod m, first x landing in [l, r]number-theory/mod-linear.cpp
n! mod p for n up to 1e9, many such queriesnumber-theory/fast-factorial.cpp
count squarefree numbers up to 1e18number-theory/squarefree-count.cpp
deque with fold (push / pop both ends)basics/sliding-window.cpp (AggregateDeque)
range mode, range LIS, range sortrange-queries/range-mode.cpp, range-lis.cpp, sortable-segment-tree.cpp
rectangle add / rectangle sum offlinerange-queries/offline-rectangle.cpp
unite a + i ~ b + i for a whole range of idata-structures/dsu.cpp (RangeParallelDSU)
potentials in a non-commutative groupdata-structures/weighted-dsu.cpp (GroupDSU)
tree DP with point updatestrees/static-top-tree.cpp
sum over vertices at distance in [lo, hi]trees/centroid-queries.cpp (ContourSum)
when does an edge join a cycle (edges added online)graphs/incremental-scc.cpp
treewidth <= 2 / series-parallel DPgraphs/treewidth-2.cpp
max independent set, all cliquesgraphs/max-clique.cpp, maximal-cliques.cpp
matroid partition, weighted matroid intersectionflows/matroid-intersection.cpp
distinct substrings of s[l..r)strings/distinct-substrings-in-range.cpp
LCS of a with every substring of bstrings/lcs-variants.cpp (seaweedKernel)
sparse series inv / exp / log / pow / sqrtpolynomial/sparse-fps.cpp
set power series exp / logpolynomial/bitwise-convolution.cpp
interpolation on a geometric sequence, Newton formpolynomial/chirp-z.cpp, newton-basis.cpp
points of B inside triangles of Ageometry/points-in-triangle.cpp
line vs convex polygon, exact anglesgeometry/convex-polygon-queries.cpp, angular-sweep.cpp
Stern-Brocot path / LCA / ancestornumber-theory/continued-fractions.cpp
stone merging (adjacent piles), alphabetic treedp/knuth-optimization.cpp (garsiaWachs)
largest subset sum <= t, small weights, huge tdp/subset-sum.cpp (maxSubsetSumAtMost)

All templates

basics/ — searching, sorting, two pointers, prefix sums, greedy, backtracking

#TemplateWhat it doesNotes
1array-classics.cppArray Classics. Boyer-Moore majority vote (and Misra-Gries for > n/k), Dutch national flag partition, and reservoir samplingMajority Element
2backtracking-puzzles.cppBacktracking Puzzles (Sudoku, knight’s tour, maze paths, word search). Bitmask Sudoku solver, Warnsdorff knight’s tour, counting simple paths in a grid maze, and word search on a letter gridBacktracking Puzzles
3backtracking.cppBacktracking and Exhaustive Generation. N-Queens with bitmasks, and generation of all subsets, k-combinations and permutations as index listsBacktracking
4binary-search.cppBinary Search. First/last integer where a monotone predicate holds, unbounded search, and real-valued bisectionBinary Search
5bit-tricks.cppBit Tricks. Bit counting helpers, submask/supermask enumeration, Gosper’s next combination, Gray code and bit reversalBit Operations
6coordinate-compression.cppCoordinate Compression. Maps arbitrary sortable values to ranks 0..k-1, preserving orderCoordinate Compression
7dancing-links.cppDancing Links (Algorithm X, exact cover). Chooses rows of a 0/1 matrix so that every column is covered exactly once; finds one solution or counts all of themDancing Links
8greedy-classics.cppGreedy Classics (intervals, Huffman, deadlines, fractional knapsack)Greedy
9kadane.cppKadane’s Maximum Subarray. Maximum-sum non-empty subarray with its bounds, the circular variant, and the maximum-sum submatrixKadane
10meet-in-the-middle.cppMeet in the Middle (Subset Sums). Sorted list of all subset sums, and counting / best subset sums against a bound by splitting the set in halfMeet in the Middle
11merge-sort-inversions.cppMerge Sort and Inversion Count. Stable bottom-up merge sort that also counts inversions (pairs i < j with a[j] < a[i])Inversions
12monotonic-stack.cppMonotonic Stack. Nearest smaller/greater element to the left and right of every position, and the largest rectangle in a histogramMonotonic Stack
13prefix-sums.cppPrefix Sums and Difference Arrays. 1D/2D prefix sums for static range sums and 1D/2D difference arrays for offline range additionsPrefix Sums
14radix-sort.cppRadix Sort. Stable LSD radix sort (8 bits per pass) for integers and for any records with an unsigned integer keySorting
15searching.cppSearching in Sorted Arrays (linear, jump, interpolation, exponential). The classic search variants on a sorted array, each returning an index of x or -1Searching
16sliding-window.cppSliding Window Aggregates. Min/max of every length-k window with a monotone deque, and a two-stack queue that aggregates any associative operationTwo Pointers
17sorting.cppSorting Algorithms (counting, merge, quick 3-way, heap, insertion, shell, bucket) and QuickselectSorting
18ternary-search.cppTernary Search. Minimum of a unimodal function over an integer range or a real interval (ternary and golden-section)Ternary Search
19two-pointers.cppTwo PointersTwo Pointers

combinatorics/ — binomials, special numbers, counting under symmetry

#TemplateWhat it doesNotes
1binomial-any-mod.cppBinomial Coefficients Modulo Any Integer. C(n, k) modulo an arbitrary m for n, k up to 1e18, via generalized Lucas modulo each prime power of m and CRTBinomial Mod m
2binomial-sums.cppSums of Binomial Coefficients. Prefix sums of a row C(n, 0..k) (single and many offline queries), and sums over a residue class sum_{i = r mod m} C(n, i)Binomial Sums
3binomial.cppBinomial CoefficientsCombinatorics
4bounded-compositions.cppBounded Compositions (stars and bars with upper bounds)Stars and Bars
5burnside-lgv.cppBurnside / Polya Counting and the LGV Lemma. Orbits under a permutation group (necklaces, bracelets, any explicit group) and non-intersecting lattice paths as a determinantBurnside
6graph-counting.cppCounting Labeled Graphs, Connected Graphs, DAGs, Trees and Forests. Tables of the numbers of labeled graphs on n vertices that are arbitrary, connected, acyclic directed, trees, rooted forestsGraph Counting
7lattice-paths.cppLattice Path Counting (obstacles, ballot / Catalan, reflection between two lines)Lattice Paths
8lucas.cppLucas’s Theorem. C(n, k) modulo a small prime p for n, k up to 1e18 by multiplying the binomials of the base-p digitsLucas Theorem
9permutation-group.cppPermutation Groups (Schreier-Sims), k-th Roots of Permutations, Factoradic Encoding. Order of and membership in the group generated by permutations; a q with q^k = p; bijection between permutations and [0, n!)Permutation Groups
10q-binomial.cppq-Binomial (Gaussian) Coefficients. [n choose k]_q modulo a prime: number of k-dimensional subspaces of F_q^n (q a prime power), or the q-analogue for any qq-Binomial
11rsk.cppRobinson-Schensted-Knuth Correspondence (Young tableaux)Robinson-Schensted-Knuth
12special-numbers.cppSpecial Number Sequences (Eulerian, Narayana, Motzkin, Schroder, Delannoy, Lah, Fubini, restricted partitions). Tables and closed forms of the counting sequences that show up behind many combinatorics problemsSpecial Numbers
13stirling-bell-partitions.cppStirling Numbers, Bell Numbers, Partitions and Derangements. Tables of Stirling numbers of both kinds, Bell numbers, integer partition numbers p(n) and derangements over any ring typeStirling and Bell

contest/ — contest setups and tooling

#TemplateWhat it doesNotes
1codejam.cppCode Jam / Kick Start / Hacker Cup Output Format. Multi-test template that prints “Case x: ” before every answerFast I/O
2fast-io.cppFast Input/Output. Buffered fread/fwrite reader and writer for integers (including __int128), strings, characters and linesFast I/O
3file-io.cppFile Input / Output (USACO, old judges). Reads NAME.in and writes NAME.out when they exist, otherwise falls back to stdin / stdoutFast I/O
4int128-io.cpp128-bit Integer I/O. Reads and prints __int128 / unsigned __int128 with the ordinary iostream operatorsFast I/O
5interactive.cppInteractive Problem Template. Query/answer helpers that flush, count queries and can be switched to an in-process stub judge for local testingInteractive
6multithreaded.cppMultithreaded Test Cases (tourist style, for offline rounds). Reads all tests, solves them in parallel threads and prints the answers in orderFast I/O
7pragmas.cppBase Template with Optimization PragmasContest Template
8random.cppTest Data GeneratorStress Testing
9stress/brute.cppStress kit: brute force. Brute force for stress.cpp: the simplest obviously-correct solution (try everything), same input formatStress Testing
10stress/checker.cppStress kit: checkerStress Testing
11stress/gen.cppStress kit: generatorStress Testing
12stress/stress.cppStress kit: runnerStress Testing

data-structures/ — DSU, balanced trees, heaps, tries, persistent and hash structures

#TemplateWhat it doesNotes
1avl-tree.cppAVL Tree (balanced BST with order statistics). Height-balanced binary search tree: insert, erase, contains, k-th smallest, rank; duplicates allowedBalanced BST
2binary-trie.cppBinary Trie (XOR Trie). Multiset of non-negative integers as a bitwise trie: min/max xor with a value, k-th smallest of x xor v, count of x xor v < kBinary Trie
3cartesian-tree.cppCartesian Tree. O(n) stack construction of the min-rooted (or any comparator) Cartesian tree of an arrayCartesian Tree
4dsu-partially-persistent.cppPartially Persistent DSU. Union-find that remembers the time of every merge, so connectivity and sizes can be asked for any past timeDisjoint Set Variants
5dsu-rollback.cppDSU with Rollback. Union-find that can undo merges in LIFO order, for offline DFS over versions or timeDisjoint Set Variants
6dsu.cppDisjoint Set Union (Union-Find). Maintains a partition of {0..n-1} under merging, with component sizesDisjoint Set Union
7dynamic-bitset.cppDynamic Bitset. Bitset with run-time size, range set/reset/flip/count, next/previous set bit, shifts and logic opsBitset
8fast-set.cppFast Set (64-ary Bitset Tree). Set of integers in [0, n) with insert, erase, contains, next (first >= x) and prev (last <= x) in O(log_64 n)Fast Set
9hash-map.cppHash Map with Anti-Hack Hash. Splitmix64 hash with a random seed for unordered_map / unordered_set / gp_hash_table, safe against anti-hash testsHash Maps
10hash-table-bloom.cppHand-written Hash Table (open addressing) and Bloom Filter. Fast fixed-capacity hash map from u64 keys with linear probing, and a Bloom filter for approximate membershipHash Table
11interval-set.cppInterval Set (Chtholly Tree / ODT). Array stored as maximal runs of equal values in a std::map, with range assign and visiting the runs of a rangeChtholly Tree
12median-heap.cppRunning Median (two heaps) and Sliding Window Median. Median of a growing stream, and the median of every window of size kRunning Median
13meldable-heap.cppMeldable Heap (Leftist Heap). Many priority queues in one node pool that can be merged in O(log n): push, top, pop and meldAdvanced Heaps
14offline-dynamic-connectivity.cppOffline Dynamic Connectivity. Connectivity under edge insertions and deletions known in advance: segment tree over time + rollback DSUDynamic Connectivity
15ordered-set.cppOrdered Set (PBDS Order-Statistics Tree). Balanced BST with k-th element and rank queries: ordered set, ordered map and ordered multisetOrdered Set
16pbds-heap-rope.cppGNU Extensions: Pairing Heap and Rope. __gnu_pbds priority queue with modify/erase/join through iterators, and __gnu_cxx::rope (persistent-ish sequence)Rope
17persistent-array.cppPersistent Array. Array with versions: reading any version and writing (which creates a new version) in O(log n)Persistence
18persistent-dsu.cppPersistent DSU. Union-find where every merge creates a new version and any old version can be queried or merged againDisjoint Set Variants
19persistent-heap.cppPersistent Leftist Heap. Meldable min-heap where push, pop and meld return new versions and never modify old onesPersistence
20persistent-queue.cppPersistent Queue and Stack. Queues and stacks with versions: push/pop on any old version creates a new versionPersistence
21persistent-treap.cppPersistent Implicit Treap. Sequence with O(log n) split/merge where every operation keeps all old versions (fast copy-paste of substrings)Persistence
22persistent-trie.cppPersistent Binary Trie. Max/min xor of x with an element of a subarray a[l, r), and counting, via prefix versions of a binary triePersistence
23queue-undo-trick.cppQueue Undo Trick. Turns any structure with “apply update / undo last update” (stack-like) into one that can also remove the OLDEST updateQueue Undo
24radix-heap.cppRadix Heap (monotone priority queue for Dijkstra)Radix Heap
25scapegoat-tree.cppScapegoat Tree (rebuilding balanced BST, ordered multiset). Balanced binary search tree without rotations: an unbalanced subtree is flattened and rebuilt perfectlyBalanced BST
26skip-list.cppSkip List. Probabilistic ordered set with expected O(log n) insert, erase, search and lower_bound, built from linked lists with random levelsSkip List
27splay-tree.cppSplay Tree (keyed multiset and implicit sequence). Self-adjusting BST: an ordered multiset with rank/k-th/predecessor queries, and a sequence with range reverse and range sumBalanced BST
28top-k-sum.cppTop-K Sum. Maintains the sum of the k largest elements of a multiset under insertions, deletions and changes of kTop-K Sum
29treap-keyed.cppKeyed Treap (FHQ Treap, split/merge by key). Ordered multiset with insert, erase, rank, k-th, predecessor/successor and subtree sums, all by split/mergeTreap
30treap.cppImplicit Treap. Sequence with insert/erase at any position, range reverse, range add, range sum/min, split and mergeTreap
31venice-heap.cppVenice Heap (Lazy Add + Small-to-Large Merge). Min-heap that supports “add x to every element” in O(1) and merging heaps by moving the smaller oneVenice Heap
32weight-balanced-tree.cppWeight-Balanced Tree (persistent ordered set with rotations, Adams / BB[alpha])Balanced BST
33weighted-dsu.cppWeighted (Potential) DSU. Union-find that maintains known differences value[v] - value[u] and detects contradictionsDisjoint Set Variants

dp/ — classic DP and every DP optimization

#TemplateWhat it doesNotes
1aliens-trick.cppAliens Trick (WQS Binary Search). Removes a “use exactly / at most k items” constraint by charging a penalty per item when the answer is concave in kAliens Trick
2broken-profile-dp.cppBroken Profile DP (Domino Tilings). Counts domino tilings of a grid with blocked cells by a cell-by-cell bitmask DP over the frontierBroken Profile
3classic-dp.cppClassic DP CollectionDynamic Programming Cheatsheet
4connected-component-dp.cppConnected Component DP (inserting elements in sorted order)Connected Component Dynamic Programming
5convex-hull-trick.cppConvex Hull Trick (Monotone Slopes). Minimum of lines y = k x + m at a point, for lines added in non-increasing order of slopeConvex Hull Trick
6cyk.cppCYK Parsing (context-free grammar membership). Decides whether a string is generated by a grammar in Chomsky normal form and counts its parse trees, by interval DPCocke-Younger-Kasami
7dag-dp.cppDP on a DAG (longest / shortest paths, path counting). Topological-order DP on a directed acyclic graph: longest and shortest paths from a source (any weights) and the number of pathsDAG Dynamic Programming
8digit-dp.cppDigit DP. Counts the integers in [0, bound] whose digits are accepted by a small finite automatonDigit Dynamic Programming
9divide-and-conquer-dp.cppDivide and Conquer DP Optimization. Layered partition DP cur[i] = min_{j < i} prev[j] + cost(j, i) when the optimal split point is monotoneDivide and Conquer Optimization
10divisor-transforms.cppDP over Divisors (zeta / Mobius on the divisor lattice)Divisor Dynamic Programming
11doubling-x2-plus-1.cppDoubling DP (“x2 / +1” trick) for Elementary Symmetric Sums. E_k(0, 1, …, n) = sum over 0 <= i_1 < … < i_k <= n of i_1 i_2 … i_k for all k <= K, in O(K^2 log n) for huge nDoubling Dynamic Programming
12dynamic-dp.cppDynamic DP on a Tree (max weight independent set with point updates). Maintains a tree DP under vertex weight changes in O(log^2 n) per update, via heavy-light decomposition and (max, +) 2x2 matricesDynamic DP
13edit-distance.cppEdit Distance (Levenshtein). Minimum cost to turn one sequence into another by insertions, deletions and substitutionsEdit Distance
14hirschberg.cppHirschberg’s Algorithm (LCS / edit alignment in linear memory). Reconstructs a longest common subsequence of two sequences in O(n m) time and O(n + m) memoryHirschberg
15knapsack.cppKnapsack (0/1, Unbounded, Bounded, Subset Sum). Maximum value within a weight capacity for 0/1, unbounded and bounded items, plus bitset subset sumsKnapsack
16knuth-optimization.cppKnuth Optimization and Garsia-Wachs. Interval DP dp[l][r] = cost(l, r) + min over splits of dp[l][m] + dp[m][r] in O(n^2) instead of O(n^3)Knuth Optimization
17lcs.cppLongest Common Subsequence. One longest common subsequence of two sequences, plus a bit-parallel LCS lengthLongest Common Subsequence
18li-chao-tree.cppLi Chao Tree. Minimum of lines and line segments y = k x + m at points of a fixed coordinate setLi Chao Tree
19line-container.cppLine Container (Dynamic Convex Hull Trick). Maximum or minimum of lines y = k x + m at a point, with lines inserted in any orderConvex Hull Trick
20lis.cppLongest Increasing Subsequence. Length and one optimal subsequence of the longest strictly increasing or non-decreasing subsequenceLongest Increasing Subsequence
21monotone-1d1d.cpp1D/1D DP with Monotone Decisions (binary search on a deque). Dp[x] = min over i < x of dp[i] + w(i, x) in O(n log n) when w satisfies the quadrangle inequality1D1D Optimization
22persistent-li-chao.cppPersistent Li Chao TreeLi Chao Tree
23plug-dp.cppPlug DP / Broken Profile with Connectivity (Hamiltonian cycles in a grid). Counts the Hamiltonian cycles through all free cells of a grid with obstacles, cell by cell with bracket-encoded plug statesBroken Profile
24product-at-most-k.cppCounting Subsets with Product at most K (floor-division states). Number of subsets (subsequences) of positive integers whose product is <= K, modulo a prime, in O(n sqrt K)Floor Division States
25rollback-cht.cppConvex Hull Trick with Rollback (CHT on a tree)Convex Hull Trick
26slope-trick.cppSlope Trick. Maintains a convex piecewise linear function with integer slopes under adds of /x - a/, prefix/suffix minima and shiftsSlope Trick
27smawk.cppSMAWK (row minima of a totally monotone matrix). For every row, the column of its leftmost minimum in a totally monotone n x m matrix given by a function, in O(n + m) evaluationsSMAWK
28sos-dp.cppSum over Subsets (Zeta / Mobius Transforms). In-place subset and superset sum transforms and their inverses over bitmasksSum over Subsets
29submask-count-dynamic.cppDynamic Submask Counting (meet in the middle on bits). Multiset of B-bit masks with insert/erase and “how many elements are submasks of s” in O(2^(B/2)) per operationDynamic Submask Count
30subset-sum.cppSubset Sum (sqrt grouping, bitset, reconstruction). Which sums are reachable by subsets of positive integers with total S, in O(S sqrt S) (or /64 with bitsets), with a witness subsetSubset Sum
31subset-union.cppSize of the Union for Every Subset of Sets (SOS). Given m sets over n elements, the size of the union of every one of the 2^m families of sets, in O(n + m 2^m)Subset Union
32tsp.cppTravelling Salesman (Held-Karp). Minimum-cost Hamiltonian cycle or path from vertex 0 by bitmask DP, with the visiting orderTravelling Salesman
33xor-equation.cppCounting Solutions of x_0 ^ x_1 ^ … ^ x_{n-1} = X with 0 <= x_i <= a_i. Number of tuples with bounded entries whose xor equals X, modulo a prime, in O(n log max)XOR Counting

flows/ — max flow, min cost flow, matchings, cuts, matroids

#TemplateWhat it doesNotes
1dinic.cppDinic’s Maximum Flow. Maximum flow, minimum s-t cut and per-edge flows in a directed networkDinic
2edmonds-karp.cppEdmonds-Karp and Ford-Fulkerson Maximum Flow. The textbook max-flow algorithms: BFS shortest augmenting paths (Edmonds-Karp) and DFS augmenting paths (Ford-Fulkerson)Edmonds-Karp
3flow-decomposition.cppFlow Decomposition (paths and cycles). Splits a feasible s-t flow into at most E augmenting paths and cycles, each with its amountFlow Decomposition
4flow-lower-bounds.cppFlow with Lower Bounds. Feasible circulation and minimum / maximum s-t flow when every edge has bounds lo <= flow <= hiLower Bounds
5general-matching.cppMaximum Matching in General Graphs (Edmonds’ Blossom). Maximum cardinality matching in an undirected graph, contracting odd cycles (blossoms)General Matching
6global-min-cut.cppGlobal Minimum Cut (Stoer-Wagner). Minimum weight set of edges whose removal disconnects an undirected weighted graphGlobal Min Cut
7gomory-hu.cppGomory-Hu Tree (All-Pairs Minimum Cut). A tree on the same vertices whose path minima equal all pairwise minimum cuts of an undirected graphGomory-Hu
8hopcroft-karp.cppHopcroft-Karp Bipartite Matching. Maximum bipartite matching in O(E sqrt V), plus a minimum vertex cover by König’s theoremHopcroft-Karp
9hungarian.cppHungarian Algorithm (Assignment Problem). Minimum-cost assignment of n rows to distinct columns of an n x m cost matrix (n <= m)Hungarian
10kuhn.cppKuhn’s Bipartite Matching (and lexicographically smallest matching). Simple augmenting-path bipartite matching, plus the lexicographically smallest maximum matchingKuhn
11matroid-intersection.cppMatroid Intersection (unweighted, weighted) and Matroid Partition. Largest set independent in two matroids at once (unweighted), with graphic, colorful (partition) and linear (xor) matroid oraclesMatroid Intersection
12max-closure.cppMaximum Weight Closure (Project Selection). Choose a set of vertices closed under “u chosen => v chosen” maximizing the total weight, via a minimum cutMax Closure
13max-density-subgraph.cppMaximum Density Subgraph. Non-empty vertex set S maximizing /E(S)/ / /S/ (edges inside S per vertex), exactly, with integer flowsDensest Subgraph
14min-cost-b-flow.cppMinimum Cost b-Flow (supplies, lower bounds, negative costs). Cheapest flow meeting vertex supplies/demands and edge bounds lo <= f <= hi with any (also negative) costs, by capacity scalingMin Cost b-Flow
15min-cost-flow-cost-scaling.cppMin Cost Max Flow by Cost Scaling (push-relabel, negative cycles allowed). Minimum cost maximum s-t flow for integer costs of any sign (negative cycles included), very fast in practiceCost Scaling
16min-cost-flow.cppMinimum-Cost Flow (Successive Shortest Paths). Min-cost max-flow (or up to a flow limit) with Dijkstra on reduced costs; negative edge costs allowedMin Cost Flow
17min-cut-unique.cppMinimum Cut Uniqueness and Cut Sides. After a max flow, the minimal source side, the minimal sink side and whether the minimum s-t cut is uniqueCut Uniqueness
18network-simplex.cppNetwork Simplex (min cost b-flow). Minimum cost flow with supplies/demands, lower bounds and any costs, by the network simplex method (block pivoting)Network Simplex
19path-cover.cppMinimum Path Cover of a DAG (vertex-disjoint and with shared vertices)Path Cover
20push-relabel.cppPush-Relabel Maximum Flow (Highest Label). Fast maximum flow value and minimum cut with highest-label selection, gap and global relabelingPush-Relabel
21randomized-matching.cppRandomized General Matching (Tutte matrix). Maximum matching size and a maximum matching of a general graph via a random Tutte matrix modulo a primeTutte Matrix
22weighted-general-matching.cppMaximum Weight Matching in General Graphs (weighted blossom). Maximum total weight matching of an undirected graph with positive integer weights, in O(n^3)Weighted Blossom
#TemplateWhat it doesNotes
1game-search.cppGame Tree Search (negamax with alpha-beta pruning and a transposition table). Minimax value and best move of a two-player zero-sum game, pruning branches that cannot change the resultMinimax
2hackenbush.cppHackenbush (green on graphs, blue-red on trees). Grundy value of Green Hackenbush on a rooted multigraph, and the surreal value of Blue-Red Hackenbush on a rooted treeHackenbush
3matching-game.cppGallai-Edmonds Decomposition and Undirected Vertex GeographyMatching Games
4retrograde.cppGames on Graphs with Cycles (retrograde analysis, loopy Sprague-Grundy)Loopy Games
5sprague-grundy.cppImpartial Games (Sprague-Grundy). Mex, Grundy value tables, Nim and misere Nim with winning moves, Wythoff’s game and nim multiplicationSprague-Grundy
6surreal-numbers.cppSurreal Numbers (dyadic rationals) for Partizan GamesHackenbush

geometry/ — 2D / 3D geometry, hulls, polygons, circles, sweeps

#TemplateWhat it doesNotes
1angular-sweep.cppAngular Sweep (circle covering, exact Angle struct, similarity transform). Maximum number of points inside or on a circle of fixed radius r placed anywhere, and a best centerAngular Sweep
2bounding-rectangle.cppMinimum Bounding Rectangle and Rectangle in RectangleBounding Rectangle
3circle-inversion.cppCircle Inversion. Inversion in a circle: maps points, and circles / lines to circles / lines, turning tangency problems into line problemsCircle Inversion
4circle-union.cppArea of a Union of Circles. Area covered by at least one of n circles (Green’s theorem over the uncovered boundary arcs)Circle Union
5circle.cppCircles. Circumcircle, circle-line and circle-circle intersections, common tangents and intersection areasCircle-Circle
6closest-pair.cppClosest Pair of Points. Pair of points with minimum Euclidean distance, by a sweep line over a y-ordered setClosest Pair
7convex-distance.cppDistance Between Two Convex Polygons. Minimum distance between two convex polygons (0 if they intersect), via the Minkowski differenceConvex Distance
8convex-hull-3d.cpp3D Convex Hull. Convex hull of points in 3D as outward-oriented triangles (incremental, exact), with surface area and volume3D Hull
9convex-hull.cppConvex Hull (Monotone Chain). Convex hull of a point set in counter-clockwise order, optionally keeping collinear boundary pointsConvex Hull
10convex-layers.cppConvex Layers (onion peeling). Peels the convex hull repeatedly; layer[i] = how many hulls were removed before point i is on the hullConvex Layers
11convex-polygon-queries.cppConvex Polygon Queries. O(log n) point location in a convex polygon, extreme vertex in a direction and tangents from a pointConvex Polygon Queries
12delaunay.cppDelaunay Triangulation and Voronoi DiagramDelaunay
13dynamic-convex-hull.cppDynamic Convex Hull (insertions only). Maintains the convex hull of a growing point set: insert a point, test whether a point is inside or on the hullDynamic Hull
14geometry-3d-extras.cpp3D Extras: Rotations (axis-angle, quaternions), Polyhedra, Spherical Geometry3D Geometry
15half-plane-intersection.cppHalf-Plane Intersection. Convex polygon (CCW) equal to the intersection of closed half-planes, by angle sort and a dequeHalf-Plane Intersection
16hull-diameter.cppRotating Calipers (Diameter and Width). Farthest pair of points and minimum width of a convex polygon with rotating calipersRotating Calipers
17kd-tree.cppk-d Tree (nearest neighbour). Static 2D tree answering “closest other point to p” by squared distanceKD Tree
18lines-segments.cppLines and Segments. Point-on-segment test, projection, distances, and line/segment intersections (exact for integers)Line Intersection
19manhattan-mst.cppManhattan Minimum Spanning Tree. Minimum spanning tree under the Manhattan distance from O(n) candidate edges (octant sweep)Manhattan Geometry
20max-collinear.cppMaximum Number of Collinear Points. Largest number of the given integer points lying on one line (duplicates count separately)Max Collinear
21min-enclosing-circle.cppMinimum Enclosing Circle (Welzl). Smallest circle containing all given points, by randomized incremental constructionEnclosing Circle
22minkowski-sum.cppMinkowski Sum of Convex Polygons. Minkowski sum {a + b} of two convex polygons in O(n + m) by merging their edges by angleMinkowski Sum
23planar-faces.cppFaces of a Planar Graph (and the outer face)Planar Faces
24point-location.cppPoint Location (offline): the segment directly below each query point. For non-crossing segments and query points, finds for every query the first segment hit by a ray shot straight downPoint Location
25point.cpp2D Point and Vector. Point with vector arithmetic, dot and cross products, orientation test and polar-angle orderVectors
26point3d.cpp3D Point, Planes and Segments. Point3 with dot and cross products and orientation, planes, line-plane intersection and 3D distances3D Geometry
27points-in-triangle.cppCount Points in Triangles (O(1) per query after O(n (n + m) log) preprocessing). Number of points of a set B strictly inside the triangle A[i] A[j] A[k] for many queries over vertices from a set APoints in Triangle
28polygon-clipping.cppPolygon Clipping, Convex Polygon Intersection, Ear-Clipping Triangulation, Affine TransformsPolygon Clipping
29polygon-union.cppArea of a Union of Polygons. Exact-up-to-precision area covered by at least one of several simple polygonsPolygon Union
30polygon.cppSimple Polygon Tools. Signed area, perimeter, point in polygon, centroid, cut by a line and lattice point counts (Pick)Polygon Area
31rectangle-union.cppUnion of Axis-Parallel Rectangles (area and perimeter). Sweep line over x with a segment tree on compressed y storing how much of the y axis is coveredRectangle Union
32segment-in-polygon.cppSegment Inside Polygon. Whether a segment lies entirely inside a simple polygon (touching the boundary is allowed), for any polygon shapeSegment in Polygon
33segment-intersection.cppSegment Intersection Detection (Shamos-Hoey) and Simple Polygon Test. Finds whether any two of n segments intersect (and one such pair), and whether a polygon is simpleSegment Intersection
34triangle.cppTriangle Centers and Formulas. Centroid, incenter, circumcenter, orthocenter, excenters, area from sides, angles and medians of a triangleTriangles

graphs/ — shortest paths, MST, connectivity, SCC, matching-free graph theory, cliques, planarity

#TemplateWhat it doesNotes
1bellman-ford.cppBellman-Ford Shortest Paths. Shortest paths with negative edge weights, marking vertices made arbitrarily cheap by negative cyclesBellman-Ford
2bfs.cppBreadth-First Search (multi-source, 0-1 BFS). Unweighted shortest paths from a set of sources with parents and paths; 0-1 BFS for 0/1 edge weightsBreadth-First Search
3biconnected-components.cppBiconnected Components and Block-Cut Tree. Splits an undirected multigraph into vertex-biconnected components (blocks), finds cut vertices and builds the block-cut treeBiconnected Components
4bipartite.cppBipartite Check (2-coloring, odd cycle). 2-colors an undirected graph or returns an odd cycle proving that it is not bipartiteBipartite Graphs
5boruvka.cppBoruvka’s Minimum Spanning Tree (and XOR MST)Boruvka
6bridges-articulation.cppBridges and Articulation Points (low-link). Finds bridges and cut vertices of an undirected multigraph with one iterative DFSBridges
7cactus.cppCactus Graph (cycles and the cactus tree). Finds the simple cycles of an edge cactus (every edge on at most one cycle) and builds its tree of vertices + cycle nodesCactus Graphs
8chinese-postman.cppChinese Postman (Route Inspection). Shortest closed walk that uses every edge of a connected undirected weighted graph at least onceChinese Postman
9chordal-graph.cppChordal Graphs (Perfect Elimination Ordering). Maximum cardinality search, chordality test, maximum clique, optimal coloring and chromatic polynomial of chordal graphsChordal Graphs
10chromatic-number.cppChromatic Number (inclusion-exclusion)Graph Coloring
11chromatic-polynomial.cppChromatic Polynomial. P(x) = number of proper colorings with at most x colors, for graphs with up to ~18 vertices, modulo a primeChromatic Polynomial
12complement-graph.cppBFS on the Complement Graph. Shortest paths (unit weights) and connected components of the complement of a sparse graph in O(n + m)Complement BFS
13count-four-cycles.cppCounting 4-Cycles. Number of 4-cycles (as edge sets) in a simple undirected graphCycle Counting
14count-triangles.cppTriangle Counting and Enumeration. Lists every triangle of an undirected graph exactly once by orienting edges from low to high degreeCycle Counting
15degree-sequence.cppDegree Sequences (Erdos-Gallai, Havel-Hakimi, Gale-Ryser, Landau)Degree Sequences
16difference-constraints.cppSystem of Difference Constraints. Finds integers x_0..x_{n-1} satisfying constraints x_v - x_u <= c (and <=, >=, == variants), or reports infeasibilityDifference Constraints
17dijkstra.cppDijkstra’s Shortest Paths. Single- or multi-source shortest paths with non-negative edge weights, parents and path reconstructionDijkstra
18directed-mst.cppDirected MST / Minimum Arborescence (Chu-Liu/Edmonds). Minimum-weight spanning arborescence rooted at a given vertex, with the chosen edges, using mergeable heaps and cycle contractionChu-Liu-Edmonds
19dominator-tree.cppDominator Tree (Lengauer-Tarjan). Immediate dominators of every vertex of a directed graph with respect to a rootDominator Tree
20dynamic-connectivity-online.cppOnline Dynamic Connectivity (Holm-de Lichtenberg-Thorup). Fully dynamic undirected graph: add edge, remove edge, connectivity and component size queries answered onlineHolm-de Lichtenberg-Thorup
21dynamic-mst-offline.cppOffline Dynamic MST (edge weight changes). MST weight after each of q offline updates “set the weight of edge i to x” on a connected graphDynamic MST
22edge-coloring.cppEdge Coloring (Bipartite with Delta colors, Vizing with Delta + 1)Edge Coloring
23euler-path.cppEuler Path / Circuit (Hierholzer). Finds a trail that uses every edge exactly once in a directed or undirected multigraph, with edge ids and existence checksEuler Path
24find-cycle.cppFind a Cycle (directed and undirected). Returns the vertices of some cycle of a directed or undirected graph, or an empty list if acyclicCycle Detection
25floyd-warshall.cppFloyd-Warshall All-Pairs Shortest Paths. All-pairs shortest paths with negative weights; pairs affected by a negative cycle get -infFloyd-Warshall
26functional-graph.cppFunctional Graphs (successor graphs: every vertex has exactly one outgoing edge). Cycles, distance to the cycle, the k-th successor for k up to 1e18, and the distance from u to v along successorsFunctional Graphs
27grid.cppGrid Graphs (BFS, multi-source, path, components, 0-1 BFS). Shortest paths and connected regions on a character grid with 4 or 8 directionsGrid Graphs
28incremental-dag-reachability.cppIncremental Reachability in a DAG (Italiano). Inserts edges into a DAG (rejecting edges that would create a cycle) and answers reachability in O(1)DAG Reachability
29incremental-scc.cppIncremental SCC (when does each edge become part of a cycle). Edges are added one by one; for each edge, the first time (prefix index) when its two endpoints are strongly connectedIncremental SCC
30johnson.cppJohnson’s All-Pairs Shortest Paths. All-pairs shortest paths on sparse graphs with negative weights (Bellman-Ford potentials + n Dijkstras)Johnson
31k-shortest-paths.cppK Shortest Walks (Eppstein). Lengths of the k shortest s-t walks (vertices and edges may repeat) with persistent leftist heapsYen
32kruskal.cppKruskal’s Minimum Spanning Tree. Minimum spanning tree (or forest) of an undirected weighted graph by sorting edges and joining components with a DSUKruskal
33max-clique.cppMaximum Clique / Maximum Independent Set (Bron-Kerbosch)Maximum Clique
34maximal-cliques.cppMaximal Clique Enumeration (Bron-Kerbosch) and Clique Counting. Calls a function for every maximal clique (with pivoting), and counts all cliques of a graph with up to ~45 verticesBron-Kerbosch
35min-diameter-spanning-tree.cppMinimum Diameter Spanning Tree (Absolute Graph Center)Minimum Diameter Tree
36min-mean-cycle.cppMinimum Mean Cycle (Karp). Minimum average edge weight over all directed cycles, as an exact fraction, with one optimal cycleMinimum Mean Cycle
37min-weight-cycle.cppMinimum Weight Cycle (Girth). Shortest cycle through every vertex, through every edge, and overall, for undirected and directed graphs with non-negative weightsGirth
38online-bridges.cppOnline Bridges (Incremental 2-Edge-Connectivity). Adds edges one by one and maintains the number of bridges and the 2-edge-connected componentsOnline Bridges
39planarity.cppPlanarity Testing (Left-Right algorithm). Decides whether an undirected graph can be drawn in the plane without crossing edgesBoyer-Myrvold
40prim.cppPrim’s Minimum Spanning Tree. Minimum spanning tree (or forest) grown from a vertex: O(n^2) on an adjacency matrix for dense graphs, heap-based for sparse onesPrim
41replacement-paths.cppReplacement Paths (Shortest Path Avoiding Each Edge). For an undirected graph with positive weights, the s-t distance when any single edge is removedReplacement Paths
42residue-shortest-path.cppShortest Paths over Residues (coin problem: which sums are representable)Residue Paths
43scc-kosaraju.cppStrongly Connected Components (Kosaraju). Two-pass SCC (DFS order on the graph, then DFS on the reverse graph), iterativeStrongly Connected Components
44scc.cppStrongly Connected Components (Tarjan). Strongly connected components of a directed graph, numbered in topological order, plus the condensation DAGStrongly Connected Components
45second-best-mst.cppSecond-Best MST and MST with a Forced EdgeSecond-Best MST
46segment-tree-graph.cppShortest Paths with Range Edges (Segment Tree Graph). Dijkstra on a graph with edges vertex -> range, range -> vertex and range -> range, using O(n) helper nodesSegment Tree Graph
47spfa.cppSPFA (Queue-Based Bellman-Ford). Single-source shortest paths with negative weights and negative-cycle detection, usually much faster than plain Bellman-FordShortest Path Faster
48st-numbering.cppst-Numbering (Bipolar Orientation). Orders the vertices from s to t so that every other vertex has a neighbour before it and a neighbour after itst-Numbering
49stable-marriage.cppStable Marriage (Gale-Shapley). Proposer-optimal stable matching; preference lists may be incomplete and the sides may differ in sizeStable Marriage
50stable-roommates.cppStable Roommates (Irving’s Algorithm)Stable Roommates
51steiner-tree.cppMinimum Steiner Tree. Minimum-weight connected subgraph containing k given terminals of an undirected graph with non-negative weights, with its edgesSteiner Tree
52strong-orientation.cppStrong Orientation (Robbins) and Min-Max Indegree Orientation hintsStrong Orientation
53three-edge-connected.cppThree-Edge-Connected Components. Partitions the vertices into classes connected by 3 edge-disjoint paths (no 2 edges disconnect them)3-Edge Connectivity
54topological-sort.cppTopological Sort (Kahn). Orders the vertices of a DAG so every edge goes forward; detects cycles; optional lexicographically smallest orderTopological Sort
55transitive-closure.cppTransitive Closure (Bitset Reachability). Answers “can u reach v” for all pairs of a directed graph with SCC condensation and bitset DPTransitive Closure
56treewidth-2.cppTree Decomposition of Width 2 (series-parallel graphs). Decides whether a graph has treewidth <= 2 and returns a tree decomposition with bags of size <= 3Treewidth 2
57two-edge-connected-components.cppTwo-Edge-Connected Components. Splits an undirected multigraph into 2-edge-connected components (no bridge inside) and builds the bridge treeBridge Tree
58two-sat.cpp2-SAT. Satisfiability of a conjunction of 2-literal clauses over boolean variables, with an assignment2-SAT
59xor-paths.cppXOR Paths in Graphs (cycle space basis). Maximum / minimum xor of a walk between two vertices of an undirected graph with xor edge weightsXOR Paths

linear-algebra/ — matrices, elimination, determinants, LP, xor bases

#TemplateWhat it doesNotes
1black-box.cppBlack-Box Linear Algebra (Freivalds’ check, Wiedemann sparse determinant). Randomized algorithms that only multiply matrices by vectors: verify A B = C, and the determinant of a sparse matrixWiedemann
2characteristic-polynomial.cppCharacteristic Polynomial. Coefficients of det(x I - A) over a field by reduction to Hessenberg form, O(n^3)Characteristic Polynomial
3determinant.cppDeterminant. Determinant of a square matrix over a field (MInt with prime modulus, doubles) or modulo any integerDeterminant
4gauss-xor.cppGaussian Elimination over GF(2). Solves a system of xor equations and computes its rank with bitset rows (64 columns per word operation)Gaussian Elimination
5gaussian-elimination.cppGaussian Elimination. Solves a system of linear equations (one solution plus a null-space basis) and computes rank, over MInt or doublesGaussian Elimination
6matrix-inverse.cppMatrix Inverse. Inverts a square matrix over MInt or doubles by Gauss-Jordan elimination on [A / I]Matrix Inverse
7matrix-mod2.cppMatrices over GF(2) with Bitsets (inverse, rank, determinant). Inverse, rank and determinant of an n x n 0/1 matrix modulo 2, with rows stored as bitsetsGF(2) Matrices
8matrix-tree.cppMatrix-Tree Theorem (Kirchhoff / Tutte). Counts spanning trees of an undirected multigraph, or spanning arborescences of a directed one, as a Laplacian determinantMatrix-Tree Theorem
9matrix.cppMatrix. Dense matrix over any ring with multiplication, fast exponentiation, identity and matrix-vector productMatrices
10min-plus-matrix.cppMin-Plus (Tropical) Matrix Power. Shortest walks with exactly k edges (or at most k), and longest walks with max-plus, for k up to 1e18Min-Plus Matrix
11permanent-hafnian.cppPermanent and HafnianPermanent
12simplex.cppSimplex (Linear Programming). Maximizes c^T x subject to A x <= b and x >= 0 with the two-phase simplex methodSimplex
13structured-matrices.cppStructured Matrices (circulant, permutant, rank-one, Vandermonde, tridiagonal, Sherman-Morrison). Determinants and solvers that exploit the structure of special matrices instead of O(n^3) eliminationStructured Matrices
14xor-basis-extra.cppXor Basis Extras (max-weight basis, range max xor, rank of a value in the span). Online maximum-weight linearly independent set, maximum subset xor inside a[l..r], and how many span values are below xXOR Basis
15xor-basis.cppXor Basis (Linear Basis over GF(2)). Maintains a basis of the xor span of inserted 64-bit numbers: membership, max/min xor, k-th smallestXOR Basis

base

#TemplateWhat it doesNotes
1main.cppContest Template

misc/ — big numbers, dates, parsing, heuristics, assorted tricks

#TemplateWhat it doesNotes
1bigint.cppArbitrary-Precision Integer (BigInt). Signed arbitrary-precision integers stored in base 1e9 with + - * / % and comparisonsBig Integers
2bump-allocator.cppBump Allocator (fast new / delete)Bump Allocator
3dates.cppCalendar Utilities. Leap years, day-of-week and conversions between a (year, month, day) date and a day numberCalendar
4expression-parser.cppExpression Parser and Evaluator. Recursive-descent evaluator for arithmetic expressions with + - * / ^, unary minus and parenthesesExpression Parsing
5fraction.cppExact Fraction Arithmetic. Rational numbers kept in lowest terms with a positive denominator, using 128-bit intermediatesFractions
6heuristic-search.cppHeuristic Search (hill climbing, beam search, genetic algorithm)Heuristics
7ida-star.cppIDA* Search (iterative deepening A*), with the 15-puzzle as exampleIterative Deepening
8interval-cover.cppInterval Cover and Constant Intervals. Fewest intervals covering a target range (greedy); splitting [from, to) into maximal runs where a function is constantGreedy
9josephus.cppJosephus Problem. Finds the survivor when n people in a circle are eliminated by counting every k-th oneJosephus
10knight-moves.cppKnight Moves on an Infinite Board. Minimum number of knight moves between two squares of an unbounded chessboard in O(1)Knight Moves
11negative-base.cppNegative Base Numbers (base -2 and any base -b). Conversion between integers and base -b digit strings, plus addition of base -2 numbers digit by digitNegative Base
12parallel-binary-search.cppParallel Binary SearchParallel Binary Search
13permutation-utils.cppPermutation Utilities. Inverse, composition, cycle decomposition, and k-th permutation / rank via Lehmer codePermutations
14set-hashing.cppSet / Multiset Hashing with Random Weights (sum hash, xor hash)Set Hashing
15simulated-annealing.cppSimulated Annealing. Generic simulated-annealing template applied to the Euclidean travelling salesman problemSimulated Annealing
16subarray-aggregates.cppSubarray Aggregates with Few Distinct Values (GCD / OR / AND over all subarrays)Subarray Aggregates
17subarray-mex.cppMEX of All Subarrays. Which values occur as the mex of some subarray, and the mex of all those mex values (CF 1436E)Subarray MEX
18trygub-number.cppTrygub Number (huge binary number under +- x 2^e)Trygub Number

number-theory/ — modint, sieves, factorization, CRT, discrete log / root, multiplicative sums

#TemplateWhat it doesNotes
1basic-number-theory.cppBasic Number Theory. Overflow-safe 64-bit modular multiply/power plus O(sqrt n) primality, factorization, divisors and Euler phiOverview
2cipolla.cppCipolla’s Algorithm (square roots modulo a prime). X with x^2 = a (mod p) by arithmetic in F_p(sqrt(w)) for a non-residue w = t^2 - aCipolla
3continued-fractions.cppContinued Fractions and the Stern-Brocot Tree. Continued fractions, convergents, closest fractions with bounded denominator and binary search over fractionsContinued Fractions
4crt.cppChinese Remainder Theorem. Solves systems x = r[i] (mod m[i]) with arbitrary (non-coprime) moduli, plus Garner’s method for the answer modulo another numberChinese Remainder Theorem
5diophantine-extra.cppMore Linear Diophantine Equations (N variables, non-negative counts). An integer solution of sum a_i x_i = c, and the number of non-negative solutions of a x + b y = c and a x + b y + c z = nDiophantine Equations
6dirichlet.cppDirichlet Convolution ToolkitDirichlet Convolution
7discrete-log.cppDiscrete Logarithm (Baby-Step Giant-Step). Smallest x >= 0 with a^x = b (mod m) for any modulus m, including gcd(a, m) > 1Discrete Log
8divisor-counting.cppDivisor Counting (smallest number with k divisors, count with exactly k divisors, sum of d(i)). Smallest n with exactly k divisors, how many n <= N have exactly k divisors, and sum_{i <= N} d(i) in about O(N^{1/3})Divisor Functions
9du-sieve.cppDu’s Sieve (Prefix Sums of phi and mu). Prefix sums of Euler’s phi and the Mobius function up to n ~ 1e10 in O(n^{2/3}) using Dirichlet convolution identitiesDu’s Sieve
10elliptic-curve.cppElliptic Curves over F_p. Points on y^2 = x^3 + a x + b (mod p): addition, doubling, scalar multiplication, point counting for small pElliptic Curves
11extended-gcd.cppExtended Euclid and Linear Diophantine Equations. Extended gcd, modular inverse for any modulus, and integer solutions of ax + by = cExtended Euclid
12factorial-mod.cppFactorials modulo a Prime for Huge n. V_p(n!) (Legendre), n! with all factors p removed modulo p for n up to 1e18, and C(n, k) mod p via itFactorial mod p
13factorization.cppMiller-Rabin and Pollard-Rho Factorization. Deterministic primality test and fast prime factorization for every 64-bit integerFactorization
14fast-factorial.cppFast Factorial mod a Prime (n up to 1e9, many queries). N! mod p for any prime p < 2^31 and n up to p - 1 (so up to ~2e9), answering many queries after one O(sqrt p log p)-ish buildFast Factorial
15fast-mod.cppFast Modular Arithmetic (Barrett, Montgomery, 64-bit mulmod). Run-time modulus reduction without division (Barrett), a Montgomery modint for odd moduli, and a * b mod m for 64-bit mFast Modulo
16fibonacci.cppFibonacci Numbers (fast doubling, Pisano period, LCM of Fibonacci numbers). F(n) mod m in O(log n), the period of Fibonacci numbers modulo m, and lcm(F(a_1), …, F(a_k)) mod pFibonacci
17floor-sum-general.cppGeneralized Floor Sum. Sum over x = 0..n of x^k1 * floor((a x + b) / c)^k2 modulo a prime, for all k1 + k2 <= K at onceFloor Sum
18floor-sum.cppFloor Sum. Computes sum_{i=0}^{n-1} floor((a * i + b) / m) in O(log m) with a Euclid-like recursionFloor Sum
19min25-sieve.cppMin_25 Sieve. Prefix sums f(1) + … + f(v) of a multiplicative f, for every v = floor(n / k), when f(p) is a polynomial in pMin_25 Sieve
20mod-linear.cppMin / Max / First Hit of (a x + b) mod mLinear Congruence
21mod-sqrt.cppSquare Root Modulo a Prime (Tonelli-Shanks). Finds x with x^2 = a (mod p) for a prime p, or reports that a is a quadratic non-residueTonelli-Shanks
22modint.cppModular Integer. Integer arithmetic modulo a compile-time or run-time modulus with automatic reductionModular Arithmetic
23modint64.cpp64-bit Modular Integer (moduli up to ~9e18). Like MInt but for moduli above 2^31 (e.gModular Arithmetic
24multiplicative-order.cppMultiplicative Order, Carmichael Function, Jacobi Symbol, Pohlig-Hellman, Pollard p - 1Multiplicative Order
25number-theory-misc.cppNumber Theory MiscellanyMiscellany
26pell.cppPell’s Equation. Fundamental solution of x^2 - D y^2 = 1 (and = -1 when it exists) via the continued fraction of sqrt(D), plus the next solutionsPell Equation
27power-tower.cppPower Towers (generalized Euler theorem). A_l ^ (a_{l+1} ^ (… ^ a_r)) mod m for any modulus, using a^x = a^(x mod phi(m) + phi(m)) when x >= log2 mPower Towers
28powerful-number-sieve.cppPowerful Number Sieve (prefix sums of multiplicative functions). F(n) = sum_{i <= n} f(i) for multiplicative f when an easy multiplicative g with g(p) = f(p) and known prefix sums G existsPowerful Numbers
29prime-counting.cppPrime Counting (Lucy_Hedgehog). Computes pi(v), the number of primes <= v, for every value v = floor(n / k) at once in O(n^{3/4})Prime Counting
30primitive-root.cppPrimitive Root, Multiplicative Order and Discrete k-th Root. Smallest primitive root modulo m, order of an element, and solutions of x^k = a (mod p) for prime pPrimitive Root
31quotient-blocks.cppQuotient Blocks. Iterates over the O(sqrt n) maximal blocks of i on which floor(n / i) is constant, and indexes all distinct values of floor(n / i)Harmonic Lemma
32segmented-sieve.cppSegmented Sieve of Eratosthenes. Enumerates the primes in a range [lo, hi) block by block using O(sqrt(hi) + block) memorySegmented Sieve
33sieve.cppLinear Sieve. Primes, smallest prime factors and optionally Euler phi and Mobius mu for all numbers up to n, with O(log x) factorizationLinear Sieve
34squarefree-count.cppCounting Squarefree Numbers up to 1e18. Q(n) = number of squarefree integers in [1, n] = sum_{d <= sqrt n} mu(d) floor(n / d^2), computed in about O(n^(2/5))Squarefree Count
35sum-of-two-squares.cppSums of Two Squares. Write a prime p = 1 (mod 4) as a^2 + b^2, list all representations n = x^2 + y^2, and count them (r2)Two Squares

numerical/ — integration and root finding

#TemplateWhat it doesNotes
1integration.cppNumerical Integration (Adaptive Simpson). Integrates a function over [a, b] with adaptive Simpson’s rule, refining only where the error estimate is largeIntegration
2poly-roots.cppReal Roots of a Polynomial. Finds all distinct real roots of a polynomial by recursing on the derivative and bisecting monotone piecesPolynomial Roots
3romberg.cppRomberg Integration and Golden-Section Search. Definite integral of a smooth function by Richardson-extrapolated trapezoids, and the minimum of a unimodal functionIntegration
4root-finding.cppRoot Finding (bisection, Newton, secant) and Complex NumbersNewton’s Method

polynomial/ — FFT / NTT, formal power series, recurrences, transforms

#TemplateWhat it doesNotes
1berlekamp-massey.cppBerlekamp-Massey. Finds the shortest linear recurrence that generates a given sequence over a fieldBerlekamp-Massey
2bitwise-convolution.cppBitwise Convolutions (XOR / AND / OR / Subset) and Set Power Series. C[k] = sum of a[i] * b[j] over i op j = k for op in xor, and, or, and the subset convolutionWalsh-Hadamard Transform
3bostan-mori.cppBostan-Mori (k-th Coefficient of a Rational Series). [x^k] P(x) / Q(x) and the k-th term of a linear recurrence of order up to ~1e5, with NTTBostan-Mori
4chirp-z.cppChirp-Z Transform (evaluation and interpolation on a geometric progression). Values f(a), f(a z), f(a z^2), …, f(a z^(m-1)) of a polynomial with one convolutionBluestein
5counting-series.cppCounting Sequences with Power Series (Stirling rows / columns, Bell, Bernoulli, partitions, power sums). O(n log n) generating-function versions of the classic combinatorial sequences, modulo an NTT primeCounting Series
6cyclotomic.cppCyclotomic Polynomials and the Factorization of x^n - 1. Exact integer coefficients of Phi_n(x), and x^n - 1 = prod over d / n of Phi_d(x) (its factorization over the rationals)Cyclotomic
7fft.cppFast Fourier Transform. Complex FFT with precise roots: real and exact-integer convolution, and convolution modulo any m < 2^31Fast Fourier Transform
8fwht-any-base.cppDigitwise Convolutions in Any Base (generalized XOR / OR / AND)Digit Convolutions
9gf2-field.cppFinite Field GF(2^64) and Carry-Less Arithmetic. Field elements as 64-bit masks (polynomials over GF(2) modulo x^64 + x^4 + x^3 + x + 1): add = xor, multiply, power, inverseGF(2^64)
10karatsuba.cppKaratsuba Multiplication (any ring). Polynomial product for coefficient types without an FFT: u64 arithmetic mod 2^64, mod any m, matrices,Karatsuba
11lagrange-interpolation.cppLagrange Interpolation. Evaluates the polynomial through f(0), …, f(n-1) at any x in O(n), or builds it from arbitrary points in O(n^2)Lagrange Interpolation
12linear-recurrence.cppK-th Term of a Linear Recurrence (Kitamasa). Computes a_k for a_i = c_1 a_{i-1} + … + c_d a_{i-d} by computing x^k mod the characteristic polynomialLinear Recurrences
13min-plus-convolution.cppMin-Plus Convolution. C_k = min over i + j = k of a_i + b_j when a is convex and b is convex too or arbitraryMin-Plus Convolution
14newton-basis.cppNewton Basis Conversion (monomial <-> Newton form on any nodes). Converts f = sum_i f_i x^i to the Newton form f = sum_i c_i prod_{j<i} (x - x_j) and back, for arbitrary (also repeated) nodesNewton Basis
15ntt-2d.cpp2D Convolution (NTT). C[i][j] = sum a[x][y] * b[i - x][j - y] for two matrices modulo an NTT prime2D Convolution
16ntt.cppNumber Theoretic Transform (+ exact 3-prime convolution). In-place NTT and polynomial multiplication modulo an NTT-friendly prime P = c * 2^k + 1Number Theoretic Transform
17online-convolution.cppOnline (Relaxed) Convolution. Returns h_i = sum f_j g_{i-j} as soon as f_i and g_i are known, so f and g may depend on h_0..h_{i-1}Online Convolution
18p-recursive.cppP-Recursive Sequences (linear recurrences with polynomial coefficients). Finds a relation sum_{i=0}^{r} P_i(n - i) a[n - i] = 0 (deg P_i <= d) from the first terms, and extends the sequence with itP-Recursive
19poly-composition.cppPower Series Composition and Compositional Inverse. F(g(x)) mod x^n, and h with g(h(x)) = x (reversion of a series), over mintComposition
20poly-euclid.cppPolynomial GCD and Inverse Modulo a Polynomial (Half-GCD). Gcd(a, b) and x with a x = 1 (mod b) for polynomials over mint, in O(n log^2 n)Polynomial GCD
21poly-factor-mod-p.cppPolynomials over F_p: Roots and Factorization (Cantor-Zassenhaus). All roots of a polynomial modulo a prime, number of distinct roots, and the complete factorization into monic irreducible factorsFactorization
22poly.cppPolynomials and Formal Power Series. Polynomial class over mint: + - *, inverse, division, log, exp, pow, sqrt, multipoint evaluation, interpolationPolynomial Arithmetic
23polynomial-sums.cppSums of Polynomials (sum a^i f(i), binomial basis)Polynomial Sums
24reeds-sloane.cppReeds-Sloane (shortest linear recurrence modulo any integer). Berlekamp-Massey for a composite modulus m: finds the shortest recurrence of a sequence mod m and computes its n-th termReeds-Sloane
25resultant.cppResultant and Naive Polynomial Euclid over a Field. Resultant Res(A, B) and polynomial remainder / gcd by schoolbook division, for any field type (no NTT needed)Resultant
26sparse-fps.cppSparse Formal Power Series (inv / exp / log / pow / sqrt in O(n k)). First n coefficients of 1 / f, exp f, log f, f^M and sqrt f when f has only k non-zero termsSparse Series
27subset-sum-count.cppCounting Subset Sums (#P Subset Sum via log / exp). For every s = 0..t, the number of subsets of a multiset of positive integers with sum s (mod 998244353)Subset Sum Counting
28taylor-shift.cppTaylor Shift and Shift of Sampling Points. Coefficients of f(x + c); values f(m), …, f(m + cnt - 1) from f(0), …, f(n - 1); sums of C(a_i, k) for all kTaylor Shift

range-queries/ — segment trees, Fenwick trees, sparse tables, Mo, wavelets, offline range tricks

#TemplateWhat it doesNotes
1cdq.cppCDQ Divide and Conquer (3D Dominance Counting). For every point, the number of other points that are <= it in all three coordinates, offlineCDQ Divide and Conquer
2disjoint-sparse-table.cppDisjoint Sparse Table. O(1) range queries on a static array for any associative operation (sum, product, matrix, …)Disjoint Sparse Table
3distinct-in-range.cppDistinct Values in Ranges. Number of distinct values in each query range, offline with a Fenwick tree (also an online variant)Distinct in Range
4dynamic-range-kth.cppDynamic Range K-th (Fenwick of Value Segment Trees). Point assignment, range k-th smallest and range rank queries on an array of values in [0, V)Dynamic Range K-th
5dynamic-segment-tree.cppDynamic (Sparse) Segment Tree. Range add and range sum over a huge coordinate range [lo, hi), creating nodes on demandDynamic Segment Tree
6fenwick-2d-range.cpp2D Fenwick Tree with Range Update and Range Query. Add v to every cell of a rectangle and ask the sum over a rectangle, both in O(log n log m)2D Fenwick
7fenwick-2d.cpp2D Fenwick Tree. Point add and rectangle sum on a grid, dense or offline over compressed coordinates2D Fenwick
8fenwick-nd.cppN-Dimensional Fenwick Tree. Point add and box sum in any fixed number of dimensions with compile-time sizesMultidimensional Fenwick
9fenwick-range.cppFenwick Tree with Range Update. Range add and range sum with two Fenwick treesRange Fenwick
10fenwick.cppFenwick Tree (Binary Indexed Tree). Point add, prefix/range sum and k-th element search on an arrayFenwick Tree
11kinetic-segment-tree.cppKinetic Segment TreeKinetic Segment Tree
12lazy-segment-tree-iterative.cppIterative Lazy Segment Tree (bottom-up). Non-recursive range update / range query with lazy tags (AtCoder Library style), with maxRight/minLeftLazy Propagation
13lazy-segment-tree.cppLazy Segment Tree. Range update (Tag) and range query (Info) with lazy propagation, plus binary search on the treeLazy Propagation
14linear-rmq.cppLinear RMQ (O(n) build, O(1) query). Range minimum queries with O(n) preprocessing using 64-element blocks with bitmask stacksLinear Range Minimum
15merge-sort-tree.cppMerge Sort Tree. Segment tree whose nodes store their range sorted, to count elements below a value in a rangeMerge Sort Tree
16mo-dsu.cppConnectivity over Edge Ranges (Mo + Rollback DSU). For queries [l, r), the number of connected components using only edges l..r-1Mo Connectivity
17mo-online.cppOnline Mo (Precomputed Block Ranges). Answers range queries online with point updates by keeping a structure for every pair of blocksOnline Mo
18mo-rollback.cppMo’s Algorithm with RollbackRollback Mo
19mo-second-offline.cppMo’s Algorithm, Second Offline (range pair counting in O(n sqrt q) with O(1) queries)Second Offline Mo
20mo-two-ranges.cppMo’s Algorithm on Two Ranges (4D Mo). Offline queries about the multiset union of two windows [l1, r1) and [l2, r2) over the same arrayTwo-Range Mo
21mo-with-updates.cppMo’s Algorithm with Updates. Offline range queries mixed with point updates, by moving a window over (l, r, time)Mo with Updates
22mo.cppMo’s Algorithm. Answers offline range queries by moving a window [l, r) with add/remove callbacks in Hilbert orderMo’s Algorithm
23offline-range-min.cppOffline Range Minimum (Arpa’s Trick). Answers all range-minimum queries offline in near-linear time with a monotone stack and a DSUArpa’s Trick
24offline-rectangle.cppOffline Rectangle Queries (rectangle sum, rectangle add + point get, rectangle add + rectangle sum)Rectangle Queries
25permutation-tree.cppPermutation Tree (析合树). Tree of all “intervals” of a permutation (subarrays whose values are consecutive), built in O(n log n)Permutation Tree
26persistent-lazy-segment-tree.cppPersistent Lazy Segment Tree (range add, range sum). Every range addition creates a new version; range sums can be asked on any versionPersistent Lazy Segment Tree
27persistent-segment-tree.cppPersistent Segment Tree. Point add creating a new version, range sum on any version, and k-th search between two versionsPersistent Segment Tree
28range-lis.cppRange LIS Queries (seaweed / unit-Monge, Tiskin)Range LIS
29range-mode.cppStatic Range Mode Query (online, O(sqrt n) per query). Most frequent value of a[l..r) and its frequency, online, for a static arrayRange Mode
30segment-tree-2d-dynamic.cppDynamic 2D Segment Tree. Online point addition and rectangle sum over huge coordinates [0, X) x [0, Y), nodes created on demandDynamic 2D Segment Tree
31segment-tree-2d.cpp2D Segment Tree. Point assignment and rectangle query on an n x m grid for any commutative monoid (sum, min, max, gcd, xor)2D Queries
32segment-tree-ap.cppSegment Tree with Arithmetic Progression Updates. Add a, a + d, a + 2d, … to a range and ask range sums (works over i64 or any modint)Arithmetic Progression Updates
33segment-tree-beats.cppSegment Tree Beats. Range chmin, range chmax and range add with range sum, min and max queriesSegment Tree Beats
34segment-tree-history.cppSegment Tree with Historic Maximum (range add / assign, max, historic max)Historic Maximum
35segment-tree-iterative.cppIterative Segment Tree (bottom-up). Non-recursive point update / range query segment tree for any monoid, with maxRight/minLeftIterative Segment Tree
36segment-tree-merge.cppSegment Tree Merging and Splitting. Many dynamic segment trees over values [0, n) in one node pool: merge two trees, split by value or by count, k-th, range countSegment Tree Merging
37segment-tree.cppSegment Tree. Point update and range query for any monoid Info, with binary search on the treeSegment Tree
38sortable-segment-tree.cppSortable Segment Tree (point set, range sort, range fold)Sortable Segment Tree
39sparse-table-2d.cpp2D Sparse Table. O(1) rectangle queries for an idempotent operation (min, max, gcd, and, or) on a static grid2D Sparse Table
40sparse-table.cppSparse Table. O(1) range queries for an idempotent operation (min, max, gcd, and, or) on a static arraySparse Table
41sqrt-decomposition.cppSqrt Decomposition. Block decomposition template with range add, range sum and range minSqrt Decomposition
42sqrt-tree.cppSqrt Tree. O(1) range queries for any associative operation (not only idempotent ones), point update in O(sqrt n)Sqrt Tree
43static-to-dynamic.cppStatic to Dynamic Transformation (Binary Grouping). Turns any static structure (build once, query many) with decomposable queries into one that supports insertionsStatic to Dynamic
44wavelet-matrix.cppWavelet Matrix. Static array answering range k-th smallest, range count of values below x, range frequency and predecessor/successorWavelet Matrix
45wavelet-tree.cppWavelet Tree. Range k-th smallest, rank, frequency and sum of values <= x, plus swapping adjacent elementsWavelet Tree
46xor-segment-tree.cppXOR Segment Tree. Sum of a[p ^ x] over a range of positions p, for any xor mask x, with point additionsXOR Segment Tree

strings/ — matching, hashing, suffix structures, palindromes, LCS

#TemplateWhat it doesNotes
1aho-corasick-dynamic.cppDynamic Aho-Corasick (insert / delete patterns online)Dynamic Aho-Corasick
2aho-corasick.cppAho-Corasick Automaton. Multi-pattern matching automaton with suffix links, dictionary links and complete goto transitionsAho-Corasick
3bitset-lcs.cppBit-Parallel LCS. Longest common subsequence lengths in O(n m / 64): stream a against a fixed b and query LCS(a so far, any prefix of b)Bit-Parallel LCS
4bitset-matching.cppBitset String Matching (Shift-And with updates)Bitset Matching
5bracket-sequence.cppBracket Sequences (matching, nesting forest, range queries)Brackets
6bwt.cppBurrows-Wheeler Transform. BWT of a string (with a sentinel) via the suffix array, and its inverseBurrows-Wheeler Transform
7de-bruijn.cppDe Bruijn Sequence. The lexicographically smallest cyclic sequence over k symbols that contains every length-n word exactly onceDe Bruijn
8distinct-substrings-in-range.cppDistinct Substrings in a Range (offline, suffix automaton + link-cut tree). For many queries [l, r), the number of distinct non-empty substrings of s[l..r)Distinct Substrings
9hashing-extra.cppHashing Extras (2D grids, point updates, deques)Hashing
10isomorphic-substrings.cppIsomorphic Substrings (hashing per letter). Answers “are s[x, x+len) and s[y, y+len) isomorphic” (a letter bijection maps one to the other) in O(sigma log sigma) per queryIsomorphic Substrings
11lcs-variants.cppLCS Variants (all substrings, cyclic rotations, semi-local seaweeds). LCS of s with every substring t[i, j] in O(/s/ /t/) total, and the maximum LCS of A with any rotation of B in O(/A/ /B/)Longest Common Subsequence
12lyndon.cppLyndon Factorization and Minimal Rotation. Duval’s algorithm for the Lyndon factorization of a string and the lexicographically smallest cyclic rotationLyndon Words
13manacher.cppManacher’s Algorithm. Longest palindrome around every center in linear time, giving O(1) palindrome checks for substringsManacher
14palindrome-factorization.cppPalindromic Factorization (eertree series links). For every prefix, the minimum number of palindromes it splits into (and one optimal split), in O(n log n)Palindromic Factorization
15palindromes-in-range.cppCounting Palindromic Substrings in a Range. Number of palindromic substrings (counted by position) of s[l, r), online, in O(log n) per queryRange Palindromes
16palindromic-tree-rollback.cppPalindromic Tree with Rollback (quick links)Eertree
17palindromic-tree.cppPalindromic Tree (Eertree). All distinct palindromic substrings of a string, built online, with occurrence counts and palindromic suffix countsEertree
18pattern-containment.cppPattern Containment Relation (which patterns are substrings of which). For a set of k strings, the full relation “pattern i occurs inside pattern j”, via Aho-Corasick and a bitset transitive closurePattern Containment
19prefix-function.cppPrefix Function (KMP). Prefix function, KMP pattern search, occurrence counts of every prefix and the prefix automatonKnuth-Morris-Pratt
20runs.cppRuns (Maximal Repetitions). All runs of a string - maximal substrings s[l, r) with smallest period t and r - l >= 2t - by Main-Lorentz divide and conquerRuns
21string-hashing.cppString Hashing (mod 2^61 - 1). Polynomial rolling hash with a random base modulo 2^61 - 1: O(1) substring hashes, LCP and comparison of substringsHashing
22subsequence-automaton.cppSubsequence Automaton (next occurrence table). For every position and letter, the next occurrence; answers “is t a subsequence of s” in O(/t/), and counts distinct subsequencesSubsequence Automaton
23suffix-array-linear.cppLinear-Time Suffix Array (SA-IS) and LCP (Kasai). Suffix array in O(n + alphabet) by induced sorting, plus the LCP array in O(n)SA-IS
24suffix-array.cppSuffix Array. Sorted suffixes, their ranks and the Kasai LCP array, with O(1) LCP queries and pattern searchSuffix Array
25suffix-automaton.cppSuffix Automaton. Minimal automaton of all substrings of one or several strings: distinct substrings, occurrence counts, longest common substringSuffix Automaton
26suffix-tree.cppSuffix Tree (Ukkonen). Online compressed trie of all suffixes, built character by character with Ukkonen’s algorithmSuffix Tree
27trie.cppTrie. Prefix tree over a multiset of strings: insert, erase, count copies of a word and words with a given prefixTrie
28wildcard-matching.cppWildcard Pattern Matching. All positions where a pattern matches a text when a wildcard symbol on either side matches any single symbol, with NTTWildcard Matching
29z-function.cppZ-Function. Z[i] = longest common prefix of s and s[i, n), plus the LCP of a pattern with every suffix of a textZ-Function
#TemplateWhat it doesNotes
1binarize-tree.cppBinarize a TreeBinarization
2centroid-decomposition.cppCentroid Decomposition. Centroid tree (parent and level of every vertex) with the distance from each vertex to all its centroid ancestorsCentroid Decomposition
3centroid-queries.cppCentroid Tree Queries (nearest marked vertex, sum of distances, contour sums). Online point updates and distance queries on a tree through the centroid decomposition (dynamic “point divide”)Centroid Decomposition
4distance-counting.cppCounting Paths of Every Length in a Tree (Centroid + FFT). Cnt[d] = number of unordered pairs of vertices at distance d (edges), for every dPath Length Counting
5dsu-on-tree.cppDSU on Tree (Small-to-Large / Sack). Answers a query for every subtree by keeping the heavy child’s data and re-adding only light subtreesSmall to Large
6dynamic-diameter.cppDynamic Tree Diameter (edge weight updates). Maintains the diameter of a weighted tree under edge weight changes, onlineDynamic Diameter
7edge-centroid-decomposition.cppEdge-Centroid DecompositionEdge Centroid
8euler-tour-tree.cppEuler Tour Tree. Dynamic forest (link, cut, reroot) with connectivity, component size/sum and subtree sums, as treaps over Euler toursEuler Tour Tree
9hld-path-queries.cppHLD + Lazy Segment Tree (path and subtree updates / queries). Ready-to-submit tree path toolkit: add to / query sum and max on any path or subtree, with vertex or edge valuesHeavy-Light Decomposition
10hld.cppHeavy-Light Decomposition. Rooted tree toolkit: LCA, distance, k-th ancestor, re-rooted queries, and O(log n) position ranges for any path or subtreeHeavy-Light Decomposition
11kruskal-reconstruction-tree.cppKruskal Reconstruction Tree. Binary tree of Kruskal merges: answers bottleneck-path queries and lists the vertices reachable using edges of weight <= xKruskal Reconstruction Tree
12ladder-kth-ancestor.cppk-th Ancestor in O(1) (Ladder Algorithm). Level ancestor queries in O(1) after O(n log n) preprocessing, using binary lifting plus long-path laddersLadder Algorithm
13lca-binary-lifting.cppBinary Lifting (LCA, k-th Ancestor, Path Aggregates). Jump tables over a weighted rooted tree for LCA, k-th ancestor and an aggregate of the edge weights on any pathBinary Lifting
14lca-rmq.cppLCA in O(1) (Euler Tour + Sparse Table). Lowest common ancestor in O(1) per query after an O(n log n) sparse-table build over the DFS orderLowest Common Ancestor
15link-cut-tree.cppLink-Cut Tree. Dynamic forest with link, cut, reroot, connectivity, LCA and ordered path aggregates in O(log n) amortizedLink-Cut Tree
16long-path-decomposition.cppLong-Path Decomposition. Lays out depth-indexed subtree DP arrays so that every vertex inherits its deepest child’s array in O(1), for O(n) total mergingLong Path
17mo-on-tree.cppMo’s Algorithm on Tree Paths. Offline path queries with add/remove callbacks by running Mo’s algorithm over the 2n-length Euler tourMo on Trees
18path-utils.cppTree Path Utilities (on path, k-th vertex on a path, path intersection). Common O(log n) questions about paths of a rooted tree, built on binary liftingPath Utilities
19persistent-centroid.cppPersistent Centroid Tree (sum of distances to a set, any version). Versions of a vertex multiset (each version = previous + one vertex) with online queries “sum of dist(v, x) over x in version k”Persistent Centroid
20prufer-code.cppPrufer Code. Linear-time bijection between labeled trees on n vertices and sequences of n-2 labelsPrüfer Code
21rerooting.cppRerooting DP. Computes a subtree DP for every choice of root at once, in O(n) calls of the combine functionsRerooting
22static-top-tree.cppStatic Top Tree (tree DP with point updates in O(log n))Static Top Tree
23top-tree.cppTop Tree (path and subtree queries on a dynamic forest). Link/cut forest supporting path aggregates, subtree aggregates (w.r.tTop Tree
24tree-diameter.cppTree Diameter, Center and Centroid. Longest path of a tree (unweighted or with non-negative weights), its center vertices, and the centroid(s)Diameter
25tree-hashing.cppTree Isomorphism and Tree Hashing. Exact isomorphism classes of rooted subtrees (AHU), canonical ids of unrooted trees, and an O(n) randomized subtree hashIsomorphism
26tree-knapsack.cppTree KnapsackTree Knapsack
27virtual-tree.cppVirtual Tree (Auxiliary Tree). Compresses a tree to k marked vertices plus their pairwise LCAs (at most 2k - 1 vertices) in O(k log n)Virtual Tree