The standard library
Map, Set, heaps, gcd, Sieve, Mod, and how to find the rest.
The library is written in CP Lang itself, and the common parts are in scope without an import. This chapter is a short tour of what a Div 2 problem reaches for, and of where to look up the rest.
Maps, sets and heaps
Press Run (Ctrl+Enter).
cnt[x] += 1works on a missing key: it starts from 0, so there is no "is it there yet?" branch. Reading a missing key withcnt[k]traps and says so;cnt.get(k)gives a?Intinstead.x in stests membership.MapandSetare hash-based; the ordered versions, with neighbour lookups likefirst_ge, areSortedMapandSortedSet.pop()returns?T,Noneon an empty heap.MaxHeapis the other direction.
Number theory
Press Run (Ctrl+Enter).
use std.math.{...} names what a program takes from a module, which is
how a reader of the solution knows where Sieve comes from.
Arithmetic modulo a prime
"Print the answer modulo 998244353" is a type. Mod<P> is an integer
modulo P; every operation reduces, so no % MOD can be forgotten:
Press Run (Ctrl+Enter).
.inv() is the inverse, and .v is the plain Int in 0..P. Mod
has no <: comparing two remainders is almost always a bug.
Finding the rest
- The library guide lists the families: graphs, trees, segment trees and Fenwick trees, strings, geometry.
- Each reference page gives every function's signature, its cost and an example that runs.
- Search (Ctrl K) finds a method by its bare name, such as
last_true.
Problem: Prime ranges
Answer q queries: how many primes lie between l and r, for 1 ≤ l ≤ r ≤ 10⁵? For 1 10 the answer is 4.
Hints
Build Sieve(N) once above the queries, then a prefix count makes each query one subtraction.
Next: Graphs.
Lints for these patterns
cpl lint, the editor and the playground flag the hand-written versions of what this chapter teaches:
hand_rolled_sieve: Hand-rolled prime or SPF sievehand_rolled_dsu: Hand-rolled union-find (DSU)hand_rolled_range_tree: Hand-rolled Fenwick or segment treefree_fold: Fold or sort of a sequence written as a free functionredundant_prelude_import:useof a name the prelude already provides