A collection of competitive programming templates and algorithms in C++.
dsu.cpp: Disjoint Set Union (Union-Find) with path compression and union by sizefen.cpp: Fenwick Tree (Binary Indexed Tree) for prefix sum querieshasher.cpp: String hashing utilitiesindexed_set.cpp: Ordered set with index-based querieslazy_seg_tree.cpp: Segment tree with lazy propagationlichao.cpp: Li Chao tree for maintaining convex hull of lineslinear_rmq.cpp: Linear-time RMQ preprocessingmonotonic_queue.cpp: Monotonic queue for sliding window problemsrmq.cpp: Range Minimum Query with sparse tableseg_tree.cpp: Standard segment tree implementationshort_lazy_seg_tree.cpp: Compact lazy segment treeshort_rmq.cpp: Compact RMQ implementationtreap.cpp: Treap (randomized binary search tree)
bellman_ford.cpp: Bellman-Ford shortest path algorithm (handles negative edges)bridges_art.cpp: Bridges and Articulation Pointsfloyd_warshall.cpp: Floyd-Warshall all-pairs shortest path algorithmbinary_lifting_lca.cpp: Lowest Common Ancestor using binary liftingcentroid.cpp: Centroid decompositiondijkstra.cpp: Dijkstra's shortest path algorithmdinic.cpp: Dinic's algorithm for maximum flowhld.cpp: Heavy-Light Decompositionlca.cpp: Lowest Common Ancestorlinear_lca.cpp: Linear-time LCA preprocessingmst.cpp: Minimum Spanning Tree using Kruskal's algorithmscc.cpp: Strongly Connected Components using Kosaraju's algorithmtoposort.cpp: Topological sort for directed acyclic graphs (DAG)
fact.cpp: Factorial and combinatorics utilitiesmod_int.cpp: Modular arithmetic with automatic modulo operations
aho_corasick.cpp: Aho-Corasick automaton for multi-pattern matchingkmp.cpp: KMP (Knuth-Morris-Pratt) pattern matching algorithmzalgo.cpp: Z-algorithm for linear-time string matching
bins.cpp: Binary search utilitiescompress_inplace.cpp: In-place coordinate compressioncompress.cpp: Coordinate compressionfast_input.cpp: Fast I/O for competitive programmingrand.cpp: Random number generation utilitiestimer.cpp: Timing and benchmarking utilitiesvec.cpp: Vector utilities and shortcuts
Each file is a self-contained implementation that can be copied directly into your solution. Most implementations use templates or classes for flexibility.
DSU dsu(n); // Initialize with n elements
dsu.merge(u, v); // Union operation
bool connected = dsu.same(u, v); // Check if in same set
int sz = dsu.size(u); // Get size of componentDijkstra<ll> dij(n); // Initialize with n nodes
dij.addedge(u, v, w); // Add edge from u to v with weight w
auto dist = dij.run(source); // Run from source, returns distance vector
auto path = dij.get_path(target); // Get shortest path to targetBellmanFord<ll> bf(n); // Initialize with n nodes
bf.addedge(u, v, w); // Add edge from u to v with weight w (can be negative)
auto dist = bf.run(source); // Run from source, returns distance vector
if (bf.has_negative_cycle()) {
// Graph contains a negative cycle reachable from source
}
auto path = bf.get_path(target); // Get shortest path to targetFloydWarshall<ll> fw(n); // Initialize with n nodes
fw.addedge(u, v, w); // Add edge from u to v with weight w (can be negative)
bool no_cycle = fw.run(); // Run algorithm, returns true if no negative cycles
if (!fw.has_negative_cycle()) {
ll dist = fw.get_dist(u, v); // Get shortest distance from u to v
auto path = fw.get_path(u, v); // Get shortest path from u to v
}using mint = ModInt<1000000007>;
mint a = 5, b = 3;
mint c = a * b + a / b; // Automatic modular arithmetic
cout << c << endl;KMP kmp("pattern"); // Initialize with pattern
auto matches = kmp.find_all("text with pattern"); // Find all occurrences
bool found = kmp.exists("text"); // Check if pattern exists
int count = kmp.count("text"); // Count occurrencesZalgo zalgo("pattern"); // Initialize with pattern
auto matches = zalgo.find_all("text with pattern"); // Find all occurrences
bool found = zalgo.exists("text"); // Check if pattern exists
int count = zalgo.count("text"); // Count occurrences
auto z = Zalgo::z_array("string"); // Compute Z-array for any stringMST<ll> mst(n); // Initialize with n nodes
mst.addedge(u, v, w); // Add edge from u to v with weight w
auto [weight, edges] = mst.run(); // Returns MST weight and edges
ll total_weight = mst.get_weight(); // Get just the weightTopoSort ts(n); // Initialize with n nodes
ts.addedge(u, v); // Add directed edge u -> v
auto order = ts.sort(); // Returns topological order, empty if cycle existsSCC scc(n); // Initialize with n nodes
scc.addedge(u, v); // Add directed edge u -> v
auto comps = scc.run(); // Returns list of components (each component is a vector of vertex indices)
int num_comps = scc.comps.size(); // Get number of components
int comp_id = scc.comp[u]; // Get component ID for vertex u
auto comp = scc.comps[scc.comp[u]]; // Get all vertices in same component as uBridgesArt ba(n); // Initialize with n nodes
ba.addedge(u, v); // Add undirected edge u-v
ba.run(); // Run the algorithm
// Bridges are stored in ba.bridges (vector of pairs)
// Articulation points are marked in ba.is_art (boolean vector)
bool is_bridge = ba.is_bridge(u, v); // Check if edge (u,v) is a bridge
bool is_art = ba.is_articulation_point(u); // Check if vertex u is an articulation pointSee STYLE.md for detailed information about the coding conventions used in this library.
You can generate a nicely formatted PDF reference document containing all implementations:
./pdf/generate.shThis will create contestlib.pdf in the repository root with syntax-highlighted code organized by category. The PDF is useful for quick reference during contests or for printing.
For detailed instructions, prerequisites, and customization options, see pdf/README.md.
Note: The PDF generation logic has been adapted and simplified from Laakeri's contestlib.
This repository includes a test framework to verify the correctness of implementations.
To run all tests:
make testTo run a specific test (e.g., DSU):
make test-dsuTo clean compiled test binaries:
make clean- Create a test file in the appropriate subdirectory of
tests/following the naming conventiontest_*.cpp - Include the implementation file using a relative path (e.g.,
#include "../../datastruct/dsu.cpp") - Write test cases using assertions
- The test will automatically be discovered and compiled by the Makefile
Example test structure:
#include "../../datastruct/dsu.cpp"
#include <cassert>
#include <iostream>
int main() {
// Test case 1
DSU dsu(5);
assert(!dsu.same(0, 1));
dsu.merge(0, 1);
assert(dsu.same(0, 1));
std::cout << "All tests passed!" << std::endl;
return 0;
}This is a personal competitive programming library. Feel free to use these implementations in your own contests or as reference material.
This code is intended for competitive programming use.