Templates, a snippet library, contest solutions, and command-line tools in C++ and Python
⚡ Quick start · 📦 What's inside · 🛠 Tools · ⚙ Setup · 📖 Notes
Lam Nguyen
After setup, from any directory:
cpnew A # ./A.cpp from the contest template
cpbuild A # sanitizers, warnings, and dbg(...) on
./solution < in.txt
cpdiff A --init # A_brute.cpp and A_gen.cpp to fill in
cpdiff A -n 1000 # stress test A.cpp against the brute force
cpgen 930 # fetch a LeetCode problem into a C++ stub
cptest 930 # run it against LeetCode's examples| Area | Contents |
|---|---|
| Contest solutions | 186: LeetCode 122, Codeforces 50, USACO 7, OI 3, AtCoder 2, ICPC 2 |
| C++ notebook | 30 snippets: data structures, databases, graphs, math, strings, trees |
| Python notebook | 37 paste-ready snippets in the same categories |
| Unit tests | 38 across the C++ and Python libraries, run with cpunit |
| Interview problems | 13, each with C++, Python, and tests |
| Templates | contest, leetcode, minimal, oi, plus gen for random tests |
| Study list | 18 sections, from searching to network communication, ticked as the notebook gains each topic |
Counted from the files in this repository
notebook/databases/ holds the structures behind real storage systems: a
Bloom filter, a count-min sketch, a cuckoo filter, a skip list, and eviction
policies.
Repository layout
templates/ contest, leetcode, minimal, and oi starters; gen for cpdiff generators
notebook/ C++ snippets to paste or include; notebook/databases/ for storage structures
python/ paste-ready Python snippets, same categories as notebook/
contests/ solutions by platform: leetcode, codeforces, atcoder, usaco, oi, icpc
interviews/ interview problems, one folder per question, each with C++, Python, and tests
todo/ a C++ study list in numbered sections, one stub per topic
tools/ cpnew, cpgen, cptest, cpunit, cpdiff
cpbuild <file.cpp>: build with sanitizers and debug output
Debug compilation with sanitizers and warnings. Passes -DLOCAL, which turns on dbg in the contest template.
cpbuild A
./solution < in.txt
The contest template (templates/contest.cpp, what cpnew copies by default) prints debug output to the terminal when built with cpbuild.
void solve() {
int n; cin >> n;
vector<int> a(n);
for (int& x : a) cin >> x;
dbg(n, a); // [n, a]: 3, [1, 2, 3]
cerr << a << '\n'; // [1, 2, 3]
}dbg prints numbers, strings, pairs, and containers: vector, set, map, and nested containers. On the judge LOCAL is off, so each dbg(...) compiles away and can stay in the submitted file.
cerr.tie(0) sits next to cin.tie(0). After cin.tie(0), the Mac C++ library drops cerr unless it is untied from cout, so a plain cerr line shows up while the program is still running.
cpnew <file> [template]: start a solution from a template
Copies a template into a new .cpp file in the current directory, or at the path you pass. It always loads templates from this repository, whatever directory you run it from. With no template argument it uses templates/contest.cpp; the others are leetcode, minimal, and oi.
cpnew A # ./A.cpp from templates/contest.cpp
cpnew A leetcode # ./A.cpp from templates/leetcode.cpp
cpnew contests/codeforces/r900/A # creates missing directories
cpnew A -f # overwrite if A.cpp exists
cpnew A --py # ./A.py from python/template.py
cpnew A leetcode --py # ./A.py from python/leetcode.py
cpgen <problem> [contest] [--weekly|--biweekly] [--upsolve]: fetch a LeetCode problem
Fetches a LeetCode problem and generates a .cpp file with the template and the method stub.
cpgen 930 # -> contests/leetcode/solve/930.cpp
cpgen 930 496 --weekly # -> contests/leetcode/solve/weekly/496/930.cpp
cpgen 930 150 --biweekly # -> contests/leetcode/solve/biweekly/150/930.cpp
cpgen 930 --upsolve # -> contests/leetcode/upsolve/930.cpp
cpgen 3891 496 --weekly --upsolve # -> contests/leetcode/upsolve/weekly/496/3891.cpp
TreeNode and ListNode definitions are generated when the problem needs them.
cptest <problem> [test] [--anyorder]: run LeetCode's examples
- The first run fetches and caches the example test cases; it does not compile or run.
- Later runs compile and test against the cached examples, with
dbg(...)output under each result. - It looks for
<number>.cppin the current directory first, then incontests/leetcode/solve/. - "Any order" problems are detected from the problem description;
--anyorderforces it. - Tree and list inputs are serialized for TreeNode and ListNode problems.
cptest 930 # fetch (first time) or run all tests
cptest 930 1 # run test 1 only
cptest 930 --anyorder # order-independent comparison
cptest 930 --add "[1,0,1]" "2" --expect "3" # add a custom test case
cptest 930 --refetch # re-fetch test cases from LeetCode
# Contest / upsolve workflow
cd contests/leetcode/solve/weekly/496 && cptest 930
cd contests/leetcode/upsolve/weekly/496 && cptest 930
Test cases are cached in contests/leetcode/tests/<number>.json, shared between solve and upsolve.
cpdiff <file> [tests...]: stress test against a brute force or test files
Runs a solution against a slow but obviously correct brute force on random tests, and stops at the first test where they disagree. The workflow follows VNOI's guide to generating tests: a generator, a brute force, and the solution, compared every round.
cpdiff A --init # create A_brute.cpp (contest template) and A_gen.cpp (templates/gen.cpp)
cpdiff A # 100 rounds: A_gen.cpp -> A_brute.cpp vs A.cpp
cpdiff A -n 1000 # 1000 rounds
cpdiff A --seed 27 -n 1 # replay the failing round
cpdiff A --brute naive --gen mygen # choose files by name (.cpp or .py)
cpdiff A tests/ # every tests/X.in against tests/X.out (or .ans)
cpdiff A 1.in 1.out # one input against one expected output
cpdiff A 1.in # one input against the brute force
cpdiff A tests/ --eps 1e-6 # numbers within 1e-6 count as equal
cpdiff A --gen A_max --no-brute -n 10 --tl 1 # timing: max-size tests, no brute force
- The brute force is found next to the solution as
A_brute,brute, ornaive; the generator asA_genorgen. Each can be.cppor.py. - The generator runs as
gen <seed>and prints one test (or writes exactly one file). Seeds go up by one per round, so any round can be replayed.templates/gen.cpphasrnd,rnd_vec,rnd_perm,rnd_str, and trees:rnd_tree,rnd_tree_prufer(uniformly random), andspecial_tree(path, star, binary, broom). - OI-style file I/O works unchanged. A program with
freopen("comnet.inp", "r", stdin)andfreopen("comnet.out", "w", stdout)gets the test incomnet.inpand is judged oncomnet.out.ifstream/ofstreamand names built from#define TASK "comnet"orconst string NAMEare detected too. Each program runs in its own folder, so the solution's.outand the brute's.ansnever collide. --no-bruteis the timing check: run the solution alone on large generated tests and report crashes, TLE, and the slowest seed.- Output is compared token by token, so spacing and trailing newlines do not matter.
--exactcompares bytes. --tl 2is the time limit per run in seconds. TLE and runtime errors (with the signal name) are reported like wrong answers.- C++ is built with
-O2 -DONLINE_JUDGE -include fstreaminto.cpdiff/A/and rebuilt only when the source changes. A failing test is saved there asfail.in,fail.ans(brute), andfail.out(solution).
WRONG ANSWER on round 6, seed 500621391
token 1 (line 1): expected '-8', got '0'
input:
2
-8 -8
expected (A_brute.cpp):
-8
got (A.cpp):
0
saved to .cpdiff/A/fail.in, fail.ans, fail.out; replay with --seed 500621391 -n 1
cpunit <name> [--cpp|--py]: run a library unit test
Finds notebook/**/tests/<name>_test.cpp and python/**/tests/test_<name>.py, builds C++ with sanitizers, runs Python with unittest, and exits nonzero on failure.
cpunit --list # every test that can be run
cpunit bloomfilter # C++ and Python tests for bloomfilter
cpunit bloomfilter --py # only the Python one
The tools are shell functions, so they work from every directory once your shell loads them. They call the scripts in this repository through CP_ROOT and do not depend on the current directory.
Clone the repository, add the block below to ~/.zshrc with CP_ROOT set to where you cloned it, then run source ~/.zshrc or open a new terminal.
Shell functions for ~/.zshrc
# Competitive programming tools. Work from any directory.
export CP_ROOT="$HOME/path/to/competitive-programming-notebook"
cpbuild() {
local src="$1"
if [[ -z $src ]]; then
echo "usage: cpbuild <file>[.cpp] [extra g++ flags...]" >&2
return 2
fi
[[ -f $src ]] || [[ ! -f $src.cpp ]] || src="$src.cpp"
if [[ ! -f $src ]]; then
echo "No such file: $1 (tried $1 and $1.cpp)" >&2
return 1
fi
shift
g++ -std=c++20 -DLOCAL -Wall -Wextra -Wshadow -fsanitize=address -fsanitize=undefined "$src" "$@" -o solution \
&& echo "Compiled $src -> solution"
}
cpnew() {
python3 "$CP_ROOT/tools/cpnew.py" "$@"
}
cpgen() {
python3 "$CP_ROOT/tools/cpgen.py" "$@"
}
cptest() {
python3 "$CP_ROOT/tools/cptest.py" "$@"
}
cpunit() {
python3 "$CP_ROOT/tools/cpunit.py" "$@"
}
cpdiff() {
python3 "$CP_ROOT/tools/cpdiff.py" "$@"
}
cprun() {
if [[ -x ./solution ]]; then
./solution "$@"
elif [[ -e ./solution ]]; then
echo "./solution exists but is not executable (chmod +x ./solution)" >&2
return 126
else
echo "No ./solution in $PWD - build one first with: cpbuild <file>.cpp" >&2
return 127
fi
}cprun runs the last build, ./solution, with any arguments you pass.
