Overview
This guide covers best practices for using C++ Algorithm Snippets effectively in competitive programming contests. Learn how to maximize speed, avoid common pitfalls, and optimize your workflow.Contest Workflow
Pre-Contest Setup
Verify Snippet Installation
Before any contest, ensure snippets are properly installed:Open in your editor and verify autocomplete works.
Speed Optimization Techniques
Fast I/O
All templates include essential I/O optimizations:What this does:
sync_with_stdio(0)- Disables synchronization between C and C++ I/O streamscin.tie(0)- Untiescinfromcoutfor faster input
Compiler Optimizations
Thetemplate_header snippet includes powerful pragmas:
Macro Shortcuts
Use built-in macros fromtemplate_header or misc_loops:
Common Problem Patterns
Pattern 1: Single Source Shortest Path
Problem Type
Problem Type
Find shortest path from one node to all others in a weighted graph.
Snippet Sequence
Snippet Sequence
Key Points
Key Points
- Use
digraphfor directed,undigraphfor undirected - Dijkstra works only with non-negative weights
- For negative weights, use
graph_bellman_ford - Returns
numeric_limits<T>::max()for unreachable nodes
Pattern 2: Range Query Problems
Problem Type
Problem Type
Process queries on array ranges (sum, min, max, update).
Snippet Sequence
Snippet Sequence
Choosing the Right Structure
Choosing the Right Structure
Fenwick Tree (
range_query_fenwick_tree_std):- Simpler implementation
- Point updates, range queries
- Sum queries only
- O(log n) operations
range_query_segment_tree):- More flexible
- Range updates possible
- Works for min, max, sum, etc.
- O(log n) operations
range_query_segment_tree_lazy_compress):- Range updates + range queries
- Essential for update-heavy problems
- O(log n) operations
Pattern 3: String Matching
Problem Type
Problem Type
Find pattern occurrences in text.
Snippet Sequence
Snippet Sequence
Algorithm Selection
Algorithm Selection
KMP (
string_kmp_std):- Single pattern matching
- O(n + m) time complexity
- No hash collisions
- Best for exact matches
string_rabin_karp_std):- Multiple pattern matching
- Rolling hash approach
- Fast in practice
- Good for approximate matching
string_aho_corasick_counter):- Multiple patterns simultaneously
- O(n + m + z) where z is matches
- Best for dictionary matching
Pattern 4: Dynamic Programming with Modular Arithmetic
Problem Type
Problem Type
Count combinations/permutations modulo large prime.
Snippet Sequence
Snippet Sequence
Usage Example
Usage Example
Debugging Strategies
Using misc_debug
Themisc_debug snippet provides powerful debugging capabilities:
Stress Testing
Usetemplate_random to generate test cases:
stress_test.cpp
Time and Space Complexity
Refer tonotes_complexity and notes_time_and_memory_limits snippets for quick reference:
Typical Contest Constraints
| N Size | Time Complexity | Algorithms |
|---|---|---|
| ≤ 10 | O(n!) | Permutations, backtracking |
| ≤ 20 | O(2^n) | Bitmask DP, subset enumeration |
| ≤ 500 | O(n³) | Floyd-Warshall, DP |
| ≤ 5,000 | O(n²) | Nested loops, simple DP |
| ≤ 100,000 | O(n log n) | Sorting, segment tree, binary search |
| ≤ 1,000,000 | O(n) | Linear algorithms, hash maps |
Memory Constraints
notes_possible_array_values snippet for detailed limits.
Common Pitfalls and Solutions
Pitfall 1: Integer Overflow
Problem
Problem
Intermediate calculations exceed
int range.Solution
Solution
Use Add
long long for intermediate calculations:misc_data_types snippet for type aliases:Pitfall 2: Modular Arithmetic Errors
Problem
Problem
Negative modulo or incorrect operations.
Solution
Solution
Use
numeric_mint_compress for automatic modular arithmetic:Pitfall 3: Array Index Errors
Problem
Problem
Off-by-one errors or zero vs one-based indexing.
Solution
Solution
Use assertions and consistent indexing:
Pitfall 4: TLE on Large Inputs
Problem
Problem
Solution times out on large test cases.
Solution
Solution
- Use Fast I/O (included in all templates):
- Optimize algorithm complexity:
- Use compressed variants:
Contest-Specific Tips
Codeforces
Use Standard Template
Handle Multiple Test Cases
Fast Modular Arithmetic
Enable Debug Mode
-DDEBUG for local testing.Google Code Jam
- Automatic case numbering:
Case #1: answer - Multiple test case handling
- Output formatting helpers
USACO
- File I/O setup
- Handles
.inand.outfiles - Proper file closing
Advanced Techniques
Small to Large Optimization
Usetree_merge_trick_on_trees for tree problems:
Coordinate Compression
Usemisc_coordinate_compression for large coordinate ranges:
Binary Jumping for Queries
Usesearches_binary_search_III for optimization:
Resource Management
Memory Optimization
Use Arrays Over Vectors
When size is known at compile time:
Reserve Vector Capacity
Avoid repeated reallocations:
Use Bitsets for Booleans
Save memory:
Reuse Data Structures
Clear and reuse instead of recreating:
Final Checklist
Before submitting:- Remove all debug statements and
log()calls - Verify time complexity is within limits
- Check for integer overflow possibilities
- Test edge cases (n=1, n=max, all same values)
- Ensure fast I/O is enabled
- Use correct graph type (directed/undirected)
- Handle modular arithmetic correctly
- Verify array bounds and indexing
- Remove unnecessary includes and snippets
- Test on sample inputs
Next Steps
Templates Overview
Explore all available templates and their use cases
API Reference
Browse complete algorithm and data structure documentation