contest-algorithms Rust Library
repository·master·Indexed 26 days ago
https://github.com/ebtech/rust-algorithmsA collection of classic data structures and algorithms implemented in Rust, designed as a 'whitebox cookbook' for students, educators, and competitive programmers. The library includes implementations for graph theory (connectivity, network flows, 2-SAT), mathematics (number theory, FFT, linear algebra), string processing (Trie, KMP, Aho-Corasick), associative range queries (ARQ), and search/ordering utilities. It also provides a Scanner for ergonomic I/O and a Cacher for memoization.
What's inside contest-algorithms
- This module provides implementations for Associative Range Query (ARQ) and Mo's Algorithm. The ARQ implementation is designed to be more general than standard segment tree implementations found in typical programming contest literature. For a deeper understanding of the specific implementation details used here, refer to the author's blog post on Codeforces.
Overview of Contest Algorithms in Rust
masterThecontest-algorithmscrate is a collection of classic data structures and algorithms implemented in Rust. It is designed as a 'whitebox cookbook' rather than a blackbox library, prioritizing usability, clarity, and conciseness to help students, educators, and competitive programmers. The implementations are optimized for being easy to modify under time pressure in programming contests.Use the Scanner utility for ergonomic I/O
masterTheScannermodule provides a utility for reading input data ergonomically, including support for both file and standard I/O, which is useful for competitive programming environments.Available Algorithm Modules
masterThe repository contains implementations for several algorithmic domains:
Graphs
- Representations: Integer index-based adjacency lists, Disjoint Set Union (DSU).
- Elementary Algorithms: Euler path/tour, Kruskal's MST, Dijkstra's shortest paths, DFS pre-order traversal.
- Connectivity: Connected components, Strongly connected components, Bridges, 2-edge-connected components, Articulation points, 2-vertex-connected components, Topological sort, 2-SAT solver.
- Network Flows: Dinic's maximum flow, Minimum cut, Hopcroft-Karp bipartite matching, Minimum cost maximum flow.
Math
- Number Theory: GCD, Bezout's identity, Miller's primality test.
- FFT: Fast Fourier Transform, Number theoretic transform, Convolution.
- Arithmetic: Rational numbers, Complex numbers, Linear algebra, Safe modular arithmetic.
Ordering and Search
- Binary search (replacements for C++
lower_bound/upper_bound), Merge sort, Coordinate compression, Online convex hull trick.
Associative Range Query (ARQ)
- Binary indexed ARQ tree (Segment tree with lazy propagation), Dynamically allocated/sparse/persistent ARQ trees, Mo's algorithm.
String Processing
- Trie, Knuth-Morris-Pratt (KMP), Aho-Corasick, Suffix array, Longest common prefix, Manacher's algorithm.
Traverse adjacency lists with AdjListIterator
masterTo iterate over the outgoing edges of a vertexu, use theadj_list(u)method. This returns anAdjListIteratorwhich yields tuples of(edge_id, destination_vertex_id).Initialize a StaticArq tree
masterUseStaticArq::new(init_val)to create a static balanced binary tree (often called a segment tree) from an initial sequence of elements. The tree requires a typeTthat implements theArqSpectrait to define the monoid operations and endomorphisms.Implement Convex Hull Trick with PiecewiseLinearConvexFn
masterPiecewiseLinearConvexFnrepresents the maximum (upper envelope) of a collection of linear functions. It uses an online version of the convex hull trick with square root decomposition for efficient amortized performance.max_with(new_m, new_b): Adds a new line with slopenew_mand interceptnew_bto the collection.evaluate(x): Evaluates the current maximum function at pointxwith good amortized runtime.
Analyze graph connectivity with ConnectivityGraph
masterThe
ConnectivityGraphstruct provides several methods to query the connectivity properties of the graph it was initialized with:cc: AVec<usize>wherecc[u]is the ID of vertexu's component (CC, SCC, or 2ECC). IDs range from 1 tonum_cc.vcc: AVec<usize>wherevcc[e]is the ID of edgee's 2VCC. IDs range from 1 tonum_vcc.num_cc: The total number of CCs, SCCs, or 2ECCs.num_vcc: The total number of 2VCCs.is_cut_vertex(u: usize) -> bool: Returnstrueif vertexuis an articulation vertex in an undirected graph.is_cut_edge(e: usize) -> bool: Returnstrueif edgeeis a bridge in an undirected graph.
Compute Z-algorithm array
masterThe
z_algorithm(text)function computes the Z-array in $O(n)$ time. For each indexi,Z[i]is the length of the longest prefix oftext[i..]that is also a prefix of the entiretext.use contest_algorithms::string_proc::z_algorithm; let z = z_algorithm(b"ababbababbabababbabababbababbaba");Compute maximum flow using Dinic's algorithm
masterThe
dinic(s, t)method implements Dinic's algorithm to find the maximum flow from sourcesto sinkt(wheres != t). It generalizes the Hopcroft-Karp algorithm for bipartite matching.Returns a tuple
(max_flow, flow)where:max_flow: The total amount of flow.flow: AVec<i64>containing the flow assigned to each edge index.
Panics
Panics if the maximum flow is $2^{63}$ or larger.
Perform coordinate compression with SparseIndex
masterSparseIndexis a data structure used for coordinate compression.- Initialize with
SparseIndex::new(coords)wherecoordsis aVec<i64>of all possible coordinates. - Use
.compress(q)to find the compressed index of a coordinateq.
compressreturns:Ok(i)if the coordinateqexists exactly at indexi.Err(i)ifqfalls between indicesi-1andi(useful for range queries).
- Initialize with
Query a range in StaticArq
masterUsequery(l, r)to return the aggregate value of the range[l, r]inclusive based on the monoid operation defined in theArqSpec.