Skip to Content
Read

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

Output
Press Run (Ctrl+Enter).
  • cnt[x] += 1 works on a missing key: it starts from 0, so there is no "is it there yet?" branch. Reading a missing key with cnt[k] traps and says so; cnt.get(k) gives a ?Int instead.
  • x in s tests membership. Map and Set are hash-based; the ordered versions, with neighbour lookups like first_ge, are SortedMap and SortedSet.
  • pop() returns ?T, None on an empty heap. MaxHeap is the other direction.

Number theory

Output
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:

Output
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.

5 tests · Ctrl+Enter
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:

On this page