CP Lang in 30 minutes
The whole language model for someone who already competes in C++: input, ranges, index spaces, optionals, the library, multitest, stress testing and submission.
You already know the algorithms. This page teaches how CP Lang writes them, in about 30 minutes. Every example runs in the page on the real compiler: press Run, edit the code or the input, and run it again. Open in playground takes any example to the full editor, with its C++17 output, Stress and Trace.
When you finish, solve a few practice problems in the browser, then
install cpl to work in your own editor and submit to Codeforces or AtCoder.
1. A program is its statements
There is no main, no includes and no fast-I/O setup. The statements run from top to
bottom, read() reads the type you ask for, and print separates its arguments with
spaces:
Press Run (Ctrl+Enter).
let binds a value that never changes and var one that does. Int is a 64-bit signed
integer. Blocks are indented, as in Python, and if, for and while end their header
with :. A short body can stay on the same line.
2. Constraints are types
Write the statement's bounds as the type. 1..=2e5 is the integers from 1 to 200,000;
[0..n]1..=1e9 is an array of n values, each from 1 to 10^9. The bounds are checked
when the input is read, they pick the smallest storage width, and they let the compiler
prove that sums don't overflow:
Press Run (Ctrl+Enter).
.. excludes its end and ..= includes it. "{total}" interpolates. Arrays come with
the obvious reductions, and a lambda is x => ...:
Press Run (Ctrl+Enter).
if is an expression, so it can sit inside print. Read a value outside its range, or
index outside an array, and the program stops with a trap that names the line and the
values, instead of running on with garbage.
3. Index spaces
Most statements number things from 1: vertices, positions, days. Declare the numbering
once with domain, and every array over it is indexed by that domain:
Press Run (Ctrl+Enter).
a[V(3)] is the third element, with no - 1 anywhere. A V can't index an array over a
different domain, so mixing up vertices and edges, or rows and columns, is a compile
error. V(3) turns a plain number into a position, and V(0) traps.
Prefix sums live on the cuts between positions: a domain of n positions has n + 1
cuts, and position v sits between cuts v.l and v.r. The off-by-one disappears:
Press Run (Ctrl+Enter).
var pre: [V.cuts]Int = 0 fills the whole array with 0. Grids take two domains,
[Row, Col]Int, indexed g[r, c]. More in Arrays and index spaces.
4. Missing is a value
C++ code marks "no answer yet" with -1 or INF and hopes no real value collides. CP
Lang writes ?Int: an Int, or None. x max= y is x = max(x, y), and on a ?Int a
None simply loses. ?? supplies the fallback at the end:
Press Run (Ctrl+Enter).
if let x = opt: runs its body only when a value is present, and opt! unwraps one you
know exists (it traps on None). A BFS keeps [V]?Int distances with no INF: see
Optionals.
5. Functions, mut and records
Parameters are read-only borrows. A function that changes its argument says mut, and so
does the caller, so a mutation is never a surprise:
Press Run (Ctrl+Enter).
A function's last expression is its value: fn sq(x: Int) -> Int = x * x is a whole
function. Functions can be nested and recursive, and they see the variables around them.
Named tuples are records, and read() reads them field by field. sort(by:) takes a key,
and tuples compare left to right, so -r.score sorts the highest score first:
Press Run (Ctrl+Enter).
enum and match are in Functions, records and match.
6. Strings and output
Str holds the text and Char one character; c - 'a' is a number:
Press Run (Ctrl+Enter).
for ... if ...: filters a loop in its header. print takes options, so most output
formats need no loop:
Press Run (Ctrl+Enter).
yes(b) prints YES or NO. Output is buffered and fast by default.
7. Lists, sorting and binary search
List<T> grows with push. Comprehensions build one in a line:
Press Run (Ctrl+Enter).
Searches on sorted data return the position of the first match, or None when there is
none, instead of an end iterator you might forget to check. first_ge and first_gt are
C++'s lower_bound and upper_bound:
Press Run (Ctrl+Enter).
Binary search on the answer is the same call on a range of candidates. first_true finds
the smallest value whose test passes, as long as the test is false then true:
Press Run (Ctrl+Enter).
No lo, hi or mid, so no off-by-one in the loop. More in
Sorting and searching.
8. The standard library
The containers you reach for in C++ are here, with the same costs. A missing Map key
reads as 0 for +=, and get returns a ?V:
Press Run (Ctrl+Enter).
Modular arithmetic is a type, so a missed % MOD can't happen:
Press Run (Ctrl+Enter).
Graphs (bfs, dijkstra, components, topo), number theory (gcd, Sieve), segment
trees, DSU and more are in the library reference. Search (Ctrl K, or
⌘K on a Mac) finds any function by name. The standard library chapter
shows how to find what you need when you don't know its name.
9. Many test cases
Write the program for one test case, then add @!multitest above it. The number of test
cases is read first, and each case runs in a fresh scope, so nothing leaks from one test
to the next:
Press Run (Ctrl+Enter).
Anything above the @!multitest line runs once and is shared, which is where a sieve or
a factorial table goes. Inside a test case, return ends that case.
10. When you are not sure: stress it
Write the slow, obviously correct version next to the fast one as @alt(program). Here
the fast solution is the largest a[j] - a[i] with i < j, keeping the minimum so far:
Press Run (Ctrl+Enter).
Open it in the playground and press Stress: it generates random inputs from the types
you declared, runs both versions, and shrinks the first disagreement to the smallest
failing input. Change best max= x - low to best max= x - a[0] and Stress finds the
bug in a moment. Trace then replays the run step by step. Locally, cpl stress a.cp
does the same. See Stress testing and the trace debugger.
11. C++ habits to leave behind
- Write
and,orandnot, andelifrather thanelse if. x min= yandx max= yreplacex = min(x, y)./and%are Euclidean: the remainder is never negative, so-7 % 3is2.- Change elements through an index (
for i in 0..n: a[i] += 1);for x in areads. - Break out of nested loops with a label:
'outer: for r in Row:andbreak 'outer.
12. Submitting
The judge runs C++, so cpl build writes one self-contained, readable C++17 file you
submit as GNU C++17:
cpl run a.cp < in.txt # run with the interpreter
cpl build a.cp --judge codeforces -o a.cpp # the file you submit--judge atcoder targets AtCoder. In the playground, the C++17 tab shows the same
file. Install cpl and the VS Code extension to work locally.
Next
- Practice: Div 2 A/B problems, judged in the browser.
- Go deeper: the chapters, one topic each.
- Keep open: the cheat sheet, the whole language on one page.