NORMAL cp-templates main 48 entries verified 2026-09-17

nihal@cp:~/competitive-programming$ cat index

Template Catalogue

48 pasteable C++ templates, indexed the way a contest actually finds them — by trigger, not by scrolling. Every entry is a struct with a test attached, not a snippet that happens to work once.

setup on a new machine, one command
bash -c "$(curl -fsSL https://raw.githubusercontent.com/mdnihal5/competitive-programming/main/install.sh)"
✓ 48 entries / 10 panes source readme snippet index
USAGEnormal mode
  1. Open a .cpp file, type normal, hit Tab — the base template.
  2. Type any trigger from a pane below (e.g. DSU, SegTree) and Tab again.
  3. Forgot a trigger? Type list, hit Tab — prints every trigger + description as a comment, read live from INDEX.md.
  4. No snippets? Press copy on a row: it copies the clean template from lib/, ready to paste under the base template.
  5. Run tests/run_all.sh — compiles + runs every template's own stress test.

Triggers never redeclare all/int/mod/N/inf — every struct is self-contained, so cards never collide when pasted together. macOS: brew install gcc astyle once.

tree -L 1competitive-programming/
. ├── Templete/ # base template, debug printer, order-statistics tree ├── Graphs/ # shortest paths, connectivity, flow, tree decomposition ├── Trees/ # weighted-tree path queries ├── Strings/ # matching automata, suffix structures, hashing ├── Maths/ # modular arithmetic, combinatorics, number theory ├── SegmentTree/ # range query / range update structures, 6 variants ├── FenwickTree/ # BIT and its range / 2D extensions ├── RMQ/ # O(1)-query sparse tables, 1D and 2D ├── DP/ # scaffolds and classic transition optimizations ├── Others/ # 3 catalogued + 4 uncatalogued (smoke-tested only) ├── vimrc/ # .vimrc, cpp.snippets, INDEX.md, bash_aliases -- see the Setup pane below └── tests/ # run_all.sh -- compiles + runs every LOCAL_TEST block
: press / to focus · esc to clear
00 BASE

Base

Templete/ the scaffold everything else pastes into 3
calltriggerwhat it doescxsrcfile
BASE01 normal base template: macros, fast IO, debug includetype normal, Tab -- everything else assumes this ran first house cpp.snippets
BASE02 PBDS order-statistics set/map -- kth element, count-less-thans.find_by_order(1); s.order_of_key(4); O(log n) standard PBDS.cpp
BASE03 debug.hpp colored pretty-printer for containers, pairs, tuplesdebug(v); debugi(arr); debugg(adj); house debug.hpp
01 GR

Graphs

Graphs/ shortest paths, connectivity, flow, decomposition 10
calltriggerwhat it doescxsrcfile
GR01 DSU disjoint-set union, path compression + union by sizeDSU d(n); d.unite(u, v); d.connected(u, v); d.compSize(u); O(a(n)) house DSU.cpp
GR02 Dijkstra shortest paths, non-negative weightsDijkstra dj(n); dj.addEdge(u, v, w); dj.run(src); dj.dist[v]; O((n+m) log n) house Dijkstra.cpp
GR03 BellmanFord shortest paths with negative weights + cycle detectionBellmanFord bf(n); bf.addEdge(u, v, w); bf.run(src); bf.dist[v]; O(n*m) KACTL BellmanFord.cpp
GR04 BinaryLift LCA, kth ancestor, distance via binary liftingbl.addEdge(u, v); bl.init(); bl.lca(u, v); bl.dist(u, v); bl.kthAncestor(u, k); O(log n) qry KACTL BinaryLifting.cpp
GR05 SCC Tarjan's strongly connected components, iterativescc.addEdge(u, v); scc.run(); scc.comp[v]; scc.sccCount; O(n+m) KACTL SCC.cpp
GR06 Bridges bridges + articulation points in one DFSba.addEdge(u, v); ba.run(); O(n+m) KACTL BridgesArticulation.cpp
GR07 TopoSort topological sort, Kahn's algorithmvector<vector<int>> adj(n); auto order = topoSort(n, adj); O(n+m) KACTL TopoSort.cpp
GR08 HLD heavy-light decomposition for path querieshld.addEdge(u, v); hld.build(); hld.lca(u, v); hld.process(u, v, [&](int l, int r) {...}); O(log^2 n) KACTL HLD.cpp
GR09 Centroid centroid decomposition of a treecd.addEdge(u, v); cd.build(); cd.centroidParent[v]; O(n log n) cp-algo CentroidDecomposition.cpp
GR10 Dinic max flow, Dinic's algorithmDinic dn(n); dn.addEdge(u, v, c); int f = dn.maxflow(s, t); O(E sqrt V) KACTL Dinic.cpp
02 TR

Trees

Trees/ weighted-tree path queries 1
calltriggerwhat it doescxsrcfile
TR01 WeightedLCA LCA + weighted path distance via binary liftingwl.lca(u,v); wl.dist(u,v); O(log n) house WeightedLCA.cpp
03 ST

Strings

Strings/ matching automata, suffix structures, hashing 5
calltriggerwhat it doescxsrcfile
ST01 ZFunction Z-function + pattern occurrencesZFunction::findOccurrences(p,t); O(n) cp-algo ZFunction.cpp
ST02 KMP prefix-function string matchingkmp.match(text); O(n+m) KACTL KMP.cpp
ST03 SuffixArray suffix array + Kasai's LCPsa.sa[i]; sa.rnk[i]; sa.lcp[i]; O(n log n) KACTL SuffixArray.cpp
ST04 AhoCorasick multi-pattern matching automatonac.addPattern(p); ac.countMatches(t); O(n+m+z) KACTL AhoCorasick.cpp
ST05 PolyHash anti-hash-test-safe polynomial hash, string or arrayh.get(l,r); h.combine(lh,rh,rlen); O(1) qry house PolyHash.cpp
04 MA

Math

Maths/ modular arithmetic, combinatorics, number theory 8
calltriggerwhat it doescxsrcfile
MA01 ModInt modular integer type with operatorsmint a = 2; cout << power(a, 3) << a / 5; using mint2 = Modular<1000000007>; O(log MOD) house ModInt.cpp
MA02 nCr nCr/nPr, auto-ready, sized to the base template's Nfac.ncr(n,r); // instantiated as fac O(1) qry house cpp.snippets
MA03 Comb nCr/nPr with a custom max-NCombinatorics C(maxN); C.nCr(a, b); C.nPr(a, b); O(1) qry house Combinatorics.cpp
MA04 CRT Chinese Remainder Theorem, two congruencesauto [x, L] = crt(a, m, b, n); O(log) KACTL CRT.cpp
MA05 Totient Euler's totient of a single valueint f = phi(n); O(sqrt n) cp-algo Totient.cpp
MA06 FastPow binary exponentiation + inverse, runtime modulusFastPow::power(b, e, m); FastPow::inverse(n, m); O(log e) house FastPow.cpp
MA07 NTT polynomial multiplication mod 998244353vector<int> c = NTT::multiply(a, b); O(n log n) KACTL NTT.cpp
MA08 Sieve linear sieve, primality + factorizationSieve sv(n); sv.isPrime(x); sv.factorize(x); sv.primes; O(N) build cp-algo primes.cpp
05 SG

Segment trees

SegmentTree/ range query / range update, five variants 6
calltriggerwhat it doescxsrcfile
SG01 SegTree iterative point-update range-query, generic opst.update(i,val); st.query(l,r); O(log n) house SegmentTree.cpp
SG02 LazySegTree range-update range-query, generic opst.Add(l,r,v); st.Sum(l,r); O(log n) house LazySegmentTree.cpp
SG03 PersistentSegTree versioned segment tree, old versions stay queryablepst.update(0,idx,val); pst.query(v2,l,r); O(log n)/ver standard PersistentSegmentTree.cpp
SG04 MergeSortTree count-less-than / order-stat range queries, staticmst.countLess(l,r,x); O(log^2 n) house MergeSortTree.cpp
SG05 MaxSubarraySeg max-subarray-sum segment tree, point-setst.modify(pos,val); st.query(l,r); O(log n) house DynamicSubarraySum.cpp
SG06 RangeToggleSum range XOR-toggle on a binary array + range sumst.toggle(l,r); st.query(l,r); O(log n) house RangeToggleSum.cpp
06 FN

Fenwick trees

FenwickTree/ BIT and its range/2D extensions 4
calltriggerwhat it doescxsrcfile
FN01 Fenwick point-update range-sum BIT + binary searchf.update(i, v); f.query(l, r); f.lower_bound(v); O(log n) house FenwickTree.cpp
FN02 FenwickRUPQ range-update point-query BITf.update(l, r, v); f.query(i); O(log n) standard FenwickRangeUpdatePointQuery.cpp
FN03 FenwickRURQ range-update range-query BIT, two-BIT trickf.update(l, r, v); f.query(l, r); O(log n) standard FenwickRangeUpdateRangeQuery.cpp
FN04 Fenwick2D 2D point-update rectangle-sum-queryf.update(x, y, v); f.query(x1, y1, x2, y2); O(log n log m) standard Fenwick2D.cpp
07 RM

RMQ

RMQ/ O(1)-query sparse tables, 1D and 2D 2
calltriggerwhat it doescxsrcfile
RM01 SparseTable O(1) RMQ, generic idempotent op (min/max/gcd)st.query(l,r); // NOT sum O(1) qry house SparseTable.cpp
RM02 RMQ2D 2D range min/max queryst.query(x1,y1,x2,y2); O(1) qry house RMQ2D.cpp
08 DP

DP scaffolds

DP/ skeletons and classic transition optimizations 6
calltriggerwhat it doescxsrcfile
DP01 DigitDP digit-DP skeleton with a worked toy exampleDigitDP dp(bound, K); int ans = dp.count(); O(dig*states) house DigitDP.cpp
DP02 BitmaskDP bitmask-DP skeleton, assignment-problem shapeBitmaskDP dp(cost); int best = dp.answer(); O(2^n * n) house BitmaskDP.cpp
DP03 SOSDP sum-over-subsets DPvector<int> g = sos(f); O(n * 2^n) cp-algo SOSDP.cpp
DP04 DnCOpt divide-and-conquer DP optimizationsolveDnC(cur, prev, 1, n, 0, n - 1, cost); cur[0] is the base case, handle it yourself. O(n log n)~ KACTL DivideAndConquerOpt.cpp
DP05 KnuthOpt Knuth's DP optimization, quadrangle inequalityKnuthOpt opt(n, [&](int i, int j) { return ...; }); int best = opt.answer(); O(n^2) KACTL KnuthOpt.cpp
DP06 CHT convex hull trick, max/min line envelopelc.add(k, m); lc.query(x); O(log n) qry KACTL ConvexHullTrick.cpp
09 MC

Misc

Others/ small single-purpose utilities 3
calltriggerwhat it doescxsrcfile
MC01 MinStack stack with running minimumms.push(5); ms.getMin(); O(1) house MinStack.cpp
MC02 PrefixSuffixMex prefix/suffix mex of an arrayprefixSuffixMex(arr); O(n) house PrefixSuffixMex.cpp
MC03 TernarySearch ternary search on a unimodal integer functionternarySearchMin(lo,hi,f); O(log n) house TernarySearch.cpp
MC04 BalMultiset multiset with lower median and sum of |v - median|BalancedMultiset s: insert(x), erase(x) (x must be present), size(), median() = LOWER medi O(log n) house BalancedMultiset.cpp
MC05 MinDeque O(1) queue with running minimum (sliding window)MinDeque d (self-contained, two stacks): push_front/push_back(x), pop_front/pop_back(), fr O(1) amortised house MinStack_Mindeque.cpp
MC06 Trie array trie: insert/erase, count words and prefixesTrie t (lowercase a-z; change ALPHA/BASE for another alphabet): insert(s) (multiset: dupli O(len) house WordTrie.cpp
MC07 DivWindow n/k minus max block frequency over divisor windowsminimumOperationsToMakeKPeriodic(word, k) (LeetCode 3137; k divides |word|): one operatio O(n) house divisor_window.cpp

-- no match for “” --

— SETUP

vimrc/

vimrc/ not a template — the Vim/UltiSnips setup this whole catalogue mirrors 4
filewhat it doesfile
.vimrc the actual Vim config — cross-platform compiler resolution (g++ on Linux, newest Homebrew g++-N on macOS), clipboard + F7 compile/run mappings.brew install gcc astyle # one-time, macOS only vimrc/vimrc
cpp.snippets every template below, as an UltiSnips trigger. No comments by design — fast to read mid-contest.normal<Tab> DSU<Tab> list<Tab> UltiSnips/cpp.snippets
INDEX.md the human-readable lookup this whole page is generated from — every trigger, description and usage example. list<Tab> reads it live.source of truth -- keep it updated when a snippet changes UltiSnips/INDEX.md
bash_aliases cstart [dir] name... — creates input.txt/output.txt + empty .cpp under $CSTART_DIR, opens it in Vim.cstart abcd a,b,c # contest abcd, opens a.cpp bash_aliases
cx = typical complexity. src = provenance — KACTL cp-algo standard textbook idiom, or house written/rebuilt for this repo (bugs found here, fixed here).