### Suffix Array Construction (Rust) Source: https://context7.com/ebtech/rust-algorithms/llms.txt Constructs a suffix array in O(n log n) time, enabling various string queries. It stores suffix starting positions in lexicographical order and provides LCP queries. ```rust use contest_algorithms::string_proc::SuffixArray; let text = b"banana"; let sa = SuffixArray::new(text.iter().cloned()); // sa.sfx contains suffix starting positions in lexicographic order // Suffixes: "a", "ana", "anana", "banana", "na", "nana" assert_eq!(sa.sfx, vec![5, 3, 1, 0, 4, 2]); // Longest common prefix of text[i..] and text[j..] let lcp = sa.longest_common_prefix(1, 3); // "anana" vs "banana" assert_eq!(lcp, 0); let lcp = sa.longest_common_prefix(1, 3); // "anana" vs "banana" let lcp2 = sa.longest_common_prefix(3, 5); // "ana" vs "na" assert_eq!(lcp2, 0); ``` -------------------------------- ### Z Algorithm for Prefix Matching in Rust Source: https://context7.com/ebtech/rust-algorithms/llms.txt Computes the Z-array for a given text, where Z[i] is the length of the longest substring starting at index i that is also a prefix of the text. This is useful for pattern matching. ```rust use contest_algorithms::string_proc::z_algorithm; let text = b"aabaaab"; let z = z_algorithm(text); // z[0] is always equal to text.length() by definition assert_eq!(z[0], 7); // z[i] = length of longest prefix of text matching text[i..] assert_eq!(z[1], 1); // "a" matches prefix "a" assert_eq!(z[3], 3); // "aab" matches prefix "aab" assert_eq!(z[4], 2); // "aa" matches prefix "aa" // Can be used for pattern matching: concatenate pattern + separator + text ``` -------------------------------- ### String Pattern Matching with KMP (Rust) Source: https://context7.com/ebtech/rust-algorithms/llms.txt Implements the Knuth-Morris-Pratt (KMP) algorithm for single-pattern string matching in linear time. It precomputes a failure function for efficient searching. ```rust use contest_algorithms::string_proc::Matcher; let pattern = b"ABA"; let text = b"ABABABA"; // Precompute failure function let matcher = Matcher::new(pattern); // Match returns length of longest prefix match at each position let matches = matcher.kmp_match(text.iter().cloned()); // matches[i] = length of pattern prefix matching text[..=i] suffix // Find all complete matches let match_positions: Vec = matches.iter() .enumerate() .filter(|(_, &len)| len == pattern.len()) .map(|(pos, _)| pos - pattern.len() + 1) .collect(); assert_eq!(match_positions, vec![0, 2, 4]); // Matches at positions 0, 2, 4 ``` -------------------------------- ### Trie (Prefix Tree) Implementation (Rust) Source: https://context7.com/ebtech/rust-algorithms/llms.txt A generic Trie (prefix tree) implementation in Rust for efficient prefix-based string storage and retrieval. Supports insertion, searching for words, and checking for prefix existence. ```rust use contest_algorithms::string_proc::Trie; let mut trie = Trie::default(); // Insert words and get node indices let node_cat = trie.insert("cat".bytes()); let node_car = trie.insert("car".bytes()); let node_card = trie.insert("card".bytes()); // Search for words assert!(trie.get("cat".bytes()).is_some()); assert!(trie.get("car".bytes()).is_some()); assert!(trie.get("dog".bytes()).is_none()); // Prefixes exist in the trie assert!(trie.get("ca".bytes()).is_some()); // node_car and node_card share the prefix "car" let car_node = trie.get("car".bytes()).unwrap(); assert_eq!(car_node, node_car); ``` -------------------------------- ### Rational Number Arithmetic (Rust) Source: https://context7.com/ebtech/rust-algorithms/llms.txt Implements exact arithmetic for fractions, automatically reducing them to their lowest terms. Supports addition, multiplication, division, and comparison operations. ```rust use contest_algorithms::math::num::Rational; let a = Rational::new(2, 3); // 2/3 let b = Rational::new(3, 4); // 3/4 let sum = a + b; assert_eq!(sum, Rational::new(17, 12)); let product = a * b; assert_eq!(product, Rational::new(1, 2)); let quotient = a / b; assert_eq!(quotient, Rational::new(8, 9)); // Automatically reduces to lowest terms let c = Rational::new(6, 9); assert_eq!(c, Rational::new(2, 3)); // Supports comparison assert!(Rational::new(1, 2) < Rational::new(2, 3)); ``` -------------------------------- ### Rust Input Scanner for Competitive Programming Source: https://context7.com/ebtech/rust-algorithms/llms.txt Provides an efficient `Scanner` utility for reading whitespace-separated tokens from standard input or files. It supports type inference via the turbofish syntax and can be used for reading various data types including primitive types, strings, and collections. File I/O can also be handled using `scanner_from_file` and `writer_to_file`. ```rust use contest_algorithms::scanner::Scanner; use std::io; // Create scanner from stdin let mut scan = Scanner::new(io::stdin().lock()); // Read tokens with type inference using turbofish syntax let n: usize = scan.token(); let x: i64 = scan.token(); let y: f64 = scan.token(); let s: String = scan.token(); // Example: read an array of n integers let mut arr = Vec::with_capacity(n); for _ in 0..n { arr.push(scan.token::()); } // For file I/O use contest_algorithms::scanner::{scanner_from_file, writer_to_file}; let mut scan = scanner_from_file("input.txt"); let mut out = writer_to_file("output.txt"); let a: i32 = scan.token(); let b: i32 = scan.token(); writeln!(out, "Sum: {}", a + b).ok(); ``` -------------------------------- ### Coordinate Compression with SparseIndex in Rust Source: https://context7.com/ebtech/rust-algorithms/llms.txt Implements coordinate compression using the `SparseIndex` struct. This utility maps large, sparse coordinate values to smaller, dense indices, which is useful for optimizing array-based algorithms. It returns `Ok(index)` for values present in the initial set and `Err(index)` for values not present, indicating their insertion position. ```rust use contest_algorithms::order::SparseIndex; // Points with large sparse coordinates let coords = vec![1_000_000, 500, 999_999_999, 1_000_000]; let index = SparseIndex::new(coords); // Compress large values to small indices assert_eq!(index.compress(500), Ok(0)); assert_eq!(index.compress(1_000_000), Ok(1)); assert_eq!(index.compress(999_999_999), Ok(2)); // Query for values not in original set assert_eq!(index.compress(499), Err(0)); // Would go before index 0 assert_eq!(index.compress(1_000_001), Err(2)); // Between indices 1 and 2 ``` -------------------------------- ### Multi-Pattern Matching with Aho-Corasick (Rust) Source: https://context7.com/ebtech/rust-algorithms/llms.txt Enables matching multiple patterns simultaneously in linear time using the Aho-Corasick algorithm. It builds an automaton from the patterns for efficient searching. ```rust use contest_algorithms::string_proc::MultiMatcher; let patterns = vec![b"he", b"she", b"his", b"hers"]; let text = b"ushers"; // Build automaton from patterns let matcher = MultiMatcher::new(patterns.iter().map(|p| p.iter().cloned())); // Match against text let match_nodes = matcher.ac_match(text.iter().cloned()); // Extract all matches: (end_position, pattern_id) let matches = matcher.get_end_pos_and_pat_id(&match_nodes); // matches contains: she ends at position 3, he ends at position 3, hers ends at position 5 assert_eq!(matches.len(), 3); assert!(matches.contains(&(3, 1))); // "she" (pattern 1) ends at position 3 assert!(matches.contains(&(3, 0))); // "he" (pattern 0) ends at position 3 assert!(matches.contains(&(5, 3))); // "hers" (pattern 3) ends at position 5 ``` -------------------------------- ### Dijkstra's Shortest Path Algorithm in Rust Source: https://context7.com/ebtech/rust-algorithms/llms.txt Computes single-source shortest paths on graphs with non-negative edge weights using Dijkstra's algorithm. It takes a graph and a vector of weights as input and returns a vector of shortest distances from a specified source vertex. Implemented within the `Graph` struct of `contest_algorithms::graph`. ```rust use contest_algorithms::graph::Graph; let mut graph = Graph::new(4, 5); graph.add_edge(0, 1); graph.add_edge(0, 2); graph.add_edge(1, 2); graph.add_edge(1, 3); graph.add_edge(2, 3); // Edge weights (parallel array to edges) let weights = vec![4, 1, 2, 5, 8]; // Find shortest paths from vertex 0 let distances = graph.dijkstra(&weights, 0); // distances[i] = shortest distance from source to vertex i assert_eq!(distances[0], 0); assert_eq!(distances[1], 4); assert_eq!(distances[2], 1); assert_eq!(distances[3], 9); ``` -------------------------------- ### Strongly Connected Components (SCC) in Rust Source: https://context7.com/ebtech/rust-algorithms/llms.txt Decomposes a directed graph into its Strongly Connected Components (SCCs). The components are returned in reverse topological order. This implementation uses Tarjan's algorithm or a similar approach provided by `ConnectivityGraph` from `contest_algorithms::graph::connectivity`. ```rust use contest_algorithms::graph::{Graph, connectivity::ConnectivityGraph}; let mut graph = Graph::new(5, 7); graph.add_edge(0, 1); graph.add_edge(1, 2); graph.add_edge(2, 0); // Cycle: 0->1->2->0 graph.add_edge(2, 3); graph.add_edge(3, 4); graph.add_edge(4, 3); // Cycle: 3->4->3 // Compute SCCs on directed graph let connectivity = ConnectivityGraph::new(&graph, true); // connectivity.cc[v] gives the SCC id for vertex v // Vertices in same SCC have same id assert_eq!(connectivity.cc[0], connectivity.cc[1]); assert_eq!(connectivity.cc[1], connectivity.cc[2]); assert_eq!(connectivity.cc[3], connectivity.cc[4]); assert!(connectivity.cc[0] != connectivity.cc[3]); assert_eq!(connectivity.num_cc, 2); // Two SCCs total ``` -------------------------------- ### Prime Factorization using Pollard's Rho Algorithm (Rust) Source: https://context7.com/ebtech/rust-algorithms/llms.txt Factors integers into their prime components using Pollard's rho algorithm. This function is efficient even for large numbers and handles edge cases like 1 and prime numbers. ```rust use contest_algorithms::math::factorize; let factors = factorize(60); assert_eq!(factors, vec![2, 2, 3, 5]); // 60 = 2^2 * 3 * 5 let factors = factorize(17); assert_eq!(factors, vec![17]); // Prime number let factors = factorize(1); assert_eq!(factors, vec![]); // Empty factorization // Works efficiently even for large numbers let large = 7156857700403137441; let factors = factorize(large); assert_eq!(factors.len(), 12); // Has 12 prime factors ``` -------------------------------- ### Dynamic Segment Tree for Sparse Ranges (AssignSum) in Rust Source: https://context7.com/ebtech/rust-algorithms/llms.txt Provides a dynamically allocated segment tree capable of handling sparse ranges, even up to 10^18 elements. It supports range updates (summation) and range queries efficiently by only allocating nodes for touched ranges. ```rust use contest_algorithms::range_query::{DynamicArq, specs::AssignSum}; // Create dynamic ARQ (not persistent) let mut arq = DynamicArq::::new(false); // Build from huge sparse range (10^18 elements) let quintillion = 1_000_000_000_000_000_000_i64; let view = arq.build_from_identity(quintillion); // Sparse updates only allocate needed nodes arq.update(view, 100, 200, &5); arq.update(view, quintillion - 100, quintillion - 1, &10); // Efficient queries on sparse structure let sum = arq.query(view, 0, quintillion - 1); assert_eq!(sum, 101 * 5 + 100 * 10); // Only updated ranges contribute // For persistent version, pass true to new() // Each update returns a new version while preserving old versions ``` -------------------------------- ### Static Range Query with Lazy Propagation (AssignMin) in Rust Source: https://context7.com/ebtech/rust-algorithms/llms.txt Implements a static segment tree supporting range updates (assigning a value) and range queries (finding the minimum) with lazy propagation. It operates on an underlying array and efficiently handles overlapping updates. ```rust use contest_algorithms::range_query::{StaticArq, specs::AssignMin}; // Initialize array of 10 zeros let mut arq = StaticArq::::new(&vec![0; 10]); // Range updates: assign value to range [l, r] arq.update(2, 4, &-5); // Set positions 2,3,4 to -5 arq.update(5, 7, &-3); // Set positions 5,6,7 to -3 arq.update(1, 6, &1); // Set positions 1,2,3,4,5,6 to 1 // Range query: minimum value in range [l, r] let min_val = arq.query(0, 9); assert_eq!(min_val, -3); // Position 7 still has -3 // Query subset let min_in_range = arq.query(5, 7); assert_eq!(min_in_range, -3); ``` -------------------------------- ### Online Convex Hull Trick in Rust Source: https://context7.com/ebtech/rust-algorithms/llms.txt Provides an `PiecewiseLinearConvexFn` for maintaining the upper envelope (maximum) of a set of linear functions. It supports online updates by adding new lines (`max_with`) and efficient queries for the maximum value at a given x-coordinate (`evaluate`). This is useful for optimizing problems involving dynamic sets of linear functions. ```rust use contest_algorithms::order::PiecewiseLinearConvexFn; let mut hull = PiecewiseLinearConvexFn::default(); // Add linear functions f(x) = mx + b hull.max_with(-1.0, 0.0); // f1(x) = -x hull.max_with(0.0, -3.0); // f2(x) = -3 hull.max_with(1.0, -8.0); // f3(x) = x - 8 // Query maximum value at specific x coordinates assert_eq!(hull.evaluate(0.0) as i64, 0); assert_eq!(hull.evaluate(1.0) as i64, -1); assert_eq!(hull.evaluate(5.0) as i64, -3); // Online: can interleave updates and queries hull.max_with(2.0, -10.0); // f4(x) = 2x - 10 assert_eq!(hull.evaluate(10.0) as i64, 10); ``` -------------------------------- ### Disjoint Set Union (Union-Find) in Rust Source: https://context7.com/ebtech/rust-algorithms/llms.txt Implements the Disjoint Set Union (DSU) data structure, also known as Union-Find, with path compression for efficient set management. It allows merging sets and finding the representative of a set. Operations are near-constant time on average. Uses `DisjointSets` from `contest_algorithms::graph`. ```rust use contest_algorithms::graph::DisjointSets; // Initialize 10 disjoint sets, each containing one element let mut dsu = DisjointSets::new(10); // Merge sets containing elements 1 and 3 dsu.merge(1, 3); dsu.merge(3, 5); dsu.merge(7, 9); // Find representatives (with path compression) assert_eq!(dsu.find(1), dsu.find(5)); // Same set assert!(dsu.find(1) != dsu.find(7)); // Different sets // Try to merge already-connected elements let merged = dsu.merge(1, 5); // Returns false (already in same set) assert!(!merged); ``` -------------------------------- ### GCD and Extended Euclidean Algorithm in Rust Source: https://context7.com/ebtech/rust-algorithms/llms.txt Implements the Extended Euclidean Algorithm (`extended_gcd`) to compute the greatest common divisor (GCD) of two integers `a` and `b`, along with coefficients `x` and `y` such that `ax + by = gcd(a, b)`. The `canon_egcd` function provides a canonical solution for linear Diophantine equations `ax + by = c`, returning the smallest non-negative `y` if a solution exists. ```rust use contest_algorithms::math::{extended_gcd, canon_egcd}; // Find gcd(a, b) and coefficients such that ax + by = gcd(a, b) let (gcd, x, y) = extended_gcd(35, 14); assert_eq!(gcd, 7); assert_eq!(35 * x + 14 * y, gcd); // Find canonical solution: ax + by = c with minimal non-negative y // Returns Some((gcd, coef_a, coef_b)) if solution exists if let Some((d, coef_a, coef_b)) = canon_egcd(14, 35, 7) { assert_eq!(d, 7); assert_eq!(14 * coef_a + 35 * coef_b, 7); assert!(coef_b >= 0); } // No solution if c is not divisible by gcd(a, b) assert_eq!(canon_egcd(14, 35, 10), None); ``` -------------------------------- ### Persistent Segment Tree (DynamicArq, AssignMin) in Rust Source: https://context7.com/ebtech/rust-algorithms/llms.txt Implements a persistent segment tree using dynamic allocation and copy-on-write semantics. This allows for creating multiple historical snapshots (versions) of the data structure, enabling queries on past states. ```rust use contest_algorithms::range_query::{DynamicArq, specs::AssignMin}; // Create persistent ARQ let mut arq = DynamicArq::::new(true); let mut view = arq.build_from_slice(&vec![0; 10]); // Save initial state let version0 = view; // Make modifications, each returns new version let version1 = arq.update(view, 2, 4, &-5); let version2 = arq.update(version1, 5, 7, &-3); let version3 = arq.update(version2, 1, 6, &1); // Query different versions independently assert_eq!(arq.query(version0, 0, 9), 0); // Original state assert_eq!(arq.query(version1, 0, 9), -5); // After first update assert_eq!(arq.query(version3, 0, 9), -3); // After all updates // All versions remain accessible ``` -------------------------------- ### Complex Number Operations (Rust) Source: https://context7.com/ebtech/rust-algorithms/llms.txt Provides floating-point complex number arithmetic suitable for applications like Fast Fourier Transform (FFT). Supports basic arithmetic operations and conversion to polar form. ```rust use contest_algorithms::math::num::{Complex, PI}; let z1 = Complex::new(3.0, 4.0); // 3 + 4i let z2 = Complex::new(1.0, -2.0); // 1 - 2i let sum = z1 + z2; assert!((sum.real - 4.0).abs() < 1e-9); assert!((sum.imag - 2.0).abs() < 1e-9); let product = z1 * z2; assert!((product.real - 11.0).abs() < 1e-9); // Real part assert!((product.imag - (-2.0)).abs() < 1e-9); // Imaginary part // Polar form: z = r * e^(iθ) let z3 = Complex::from_polar(2.0, PI / 4.0); assert!((z3.real - 2.0_f64.sqrt()).abs() < 1e-9); let magnitude_sq = z1.abs_square(); assert_eq!(magnitude_sq, 25.0); ``` -------------------------------- ### Binary Search Lower and Upper Bounds in Rust Source: https://context7.com/ebtech/rust-algorithms/llms.txt Implements `slice_lower_bound` and `slice_upper_bound` functions for sorted slices, analogous to C++ STL's `std::lower_bound` and `std::upper_bound`. These functions efficiently find the first index where an element can be inserted while maintaining order, or the first element greater than the key. ```rust use contest_algorithms::order::{slice_lower_bound, slice_upper_bound}; let sorted = vec![1, 2, 4, 4, 4, 7, 9]; // Lower bound: minimum i where sorted[i] >= key let lb = slice_lower_bound(&sorted, &4); assert_eq!(lb, 2); // First occurrence of 4 // Upper bound: minimum i where sorted[i] > key let ub = slice_upper_bound(&sorted, &4); assert_eq!(ub, 5); // First element after all 4s // For non-existent elements assert_eq!(slice_lower_bound(&sorted, &5), 5); // Position where 5 would go assert_eq!(slice_upper_bound(&sorted, &10), 7); // Past the end ``` -------------------------------- ### Graph Construction and Operations in Rust Source: https://context7.com/ebtech/rust-algorithms/llms.txt Constructs and manipulates graphs using an adjacency list representation. Supports adding directed and undirected edges, iterating through adjacency lists, and querying graph properties like the number of vertices and edges. It utilizes a `Graph` struct from the `contest_algorithms::graph` module. ```rust use contest_algorithms::graph::Graph; // Create a graph with 5 vertices, hint that ~6 edges will be added let mut graph = Graph::new(5, 6); // Add directed edges graph.add_edge(0, 1); graph.add_edge(1, 2); graph.add_edge(2, 3); // Add undirected edges (creates two directed edges) graph.add_undirected_edge(3, 4); graph.add_undirected_edge(0, 4); // Iterate through adjacency list for (edge_id, vertex) in graph.adj_list(0) { println!("Edge {} points to vertex {}", edge_id, vertex); } // Query graph properties assert_eq!(graph.num_v(), 5); assert_eq!(graph.num_e(), 7); // 3 directed + 2 undirected (counted as 4) ``` -------------------------------- ### Dinic's Algorithm: Maximum Flow in Rust Source: https://context7.com/ebtech/rust-algorithms/llms.txt Computes the maximum flow in a flow network using Dinic's algorithm. It requires a `FlowGraph` structure with pre-defined edges and capacities. The function returns the maximum flow value and the flow on each edge. ```rust use contest_algorithms::graph::flow::FlowGraph; // Create flow network with 4 vertices let mut flow_graph = FlowGraph::new(4, 5); // add_edge(from, to, forward_capacity, reverse_capacity, cost_per_unit) flow_graph.add_edge(0, 1, 10, 0, 0); // Source to intermediate flow_graph.add_edge(0, 2, 10, 0, 0); // Source to intermediate flow_graph.add_edge(1, 3, 4, 0, 0); // Intermediate to sink flow_graph.add_edge(2, 3, 8, 0, 0); // Intermediate to sink flow_graph.add_edge(1, 2, 2, 0, 0); // Cross edge let source = 0; let sink = 3; // Returns (max_flow_value, flow_on_each_edge) let (max_flow, flow) = flow_graph.dinic(source, sink); assert_eq!(max_flow, 12); // flow[e] contains the flow value on edge e ``` -------------------------------- ### Palindrome Detection using Manacher's Algorithm in Rust Source: https://context7.com/ebtech/rust-algorithms/llms.txt Finds all palindromic substrings in linear time using Manacher's Algorithm. It returns an array of palindrome lengths centered at each position, differentiating between odd and even length palindromes. ```rust use contest_algorithms::string_proc::palindromes; let text = b"banana"; // Returns palindrome lengths at each center position // pal[2*i] = odd-length palindrome centered at text[i] // pal[2*i+1] = even-length palindrome centered between text[i] and text[i+1] let pal = palindromes(text); // pal = [1, 0, 1, 0, 3, 0, 5, 0, 3, 0, 1] // Position 3 (between 'a' and 'n'): even palindrome length 0 // Position 6 (at middle 'n'): odd palindrome "anana" length 5 assert_eq!(pal[6], 5); // "anana" centered at text[3] assert_eq!(pal[4], 3); // "ana" centered at text[2] ``` -------------------------------- ### Miller-Rabin Primality Test in Rust Source: https://context7.com/ebtech/rust-algorithms/llms.txt Provides a deterministic Miller-Rabin primality test function (`is_prime`) suitable for 64-bit integers. This function efficiently determines if a given number is prime within a reasonable range. It correctly identifies small primes, large primes, and composite numbers. ```rust use contest_algorithms::math::is_prime; assert!(is_prime(2)); assert!(is_prime(17)); assert!(is_prime(1_000_000_007)); assert!(is_prime((1i64 << 61) - 1)); // Large Mersenne prime assert!(!is_prime(1)); assert!(!is_prime(4)); assert!(!is_prime(1_000_000)); assert!(!is_prime(1_000_000_008)); ``` -------------------------------- ### Minimum Spanning Tree (Kruskal's) in Rust Source: https://context7.com/ebtech/rust-algorithms/llms.txt Finds the Minimum Spanning Tree (MST) of an undirected weighted graph using Kruskal's algorithm. It identifies the set of edges with the minimum total weight that connects all vertices without forming cycles. The function returns the indices of the edges included in the MST. Requires `Graph` from `contest_algorithms::graph`. ```rust use contest_algorithms::graph::Graph; let mut graph = Graph::new(4, 10); graph.add_undirected_edge(0, 1); graph.add_undirected_edge(0, 2); graph.add_undirected_edge(1, 2); graph.add_undirected_edge(1, 3); graph.add_undirected_edge(2, 3); // Weights for each undirected edge (not each directed edge) let weights = vec![10, 6, 5, 15, 4]; // Returns indices of edges in the MST let mst_edges = graph.min_spanning_tree(&weights); // Calculate total MST weight let total_weight: i64 = mst_edges.iter() .map(|&e| weights[e]) .sum(); assert_eq!(total_weight, 19); // Edges with weights 4, 5, 10 ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.