# Ownership, lends & borrowing URL: /docs/guides/borrowing Variables own their values. Function parameters borrow them for the call. A projection lets a caller work on part of a value—a row, a slice, or an element—without allocating a copy or keeping a reference for later. > **Implementation status.** Struct projections with `lends` / `lends mut` and explicit `mut` parameters run directly in `cpl` and the browser WebAssembly playground. Custom `@law disjoint` proofs and generic library projections are part of the specification and are rolling out incrementally across the compiler. ## Own it, borrow it, or copy it ```cp domain V = 1..=3 var a: [V]Int = 2 fn total(a: [V]Int) -> Int: a.sum() fn bump(mut a: [V]Int, v: V): a[v] += 1 print(total(a)) // read-only borrow, no array copy bump(mut a, V(1)) // mutable borrow, explicit at both ends let saved = a.copy() // an owned copy, explicit cost ``` While a place is borrowed mutably, other code cannot read or write the same place. Multiple read-only borrows are fine. Separate struct fields can be borrowed separately; overlapping container accesses need more evidence. ## A projection lends a place An ordinary function uses `->` to return an owned value. A projection returns `-> lends T` to give temporary access to a place in its receiver, and the tail expression of its body names that place (`mut place` for a mutable one). `lends` is one of only four library-author keywords; contestants use projections, they rarely write them. ```cp domain V = 1..=3 struct Counter: data: [V]Int fn at(mut self, i: V) -> lends mut Int: mut self.data[i] var counter = Counter([V] v => 0) counter.at(V(1)) += 7 print(counter.data) ``` This projection lends one counter without copying it. `lends T` only permits reading. `lends mut T` permits mutation when the caller holds the receiver mutably and the use asks for mutation. It does not turn a read-only receiver into a mutable one. ```cp struct Value: data: Int fn get(self) -> lends Int: self.data let owner = Value(7) let lent = owner.get() print(lent) ``` The local `lent` is temporary access to `owner`, not an independent owner. A mutating projection use such as `counter.at(i) += 1` holds its mutable lend for that statement. Generic grid-row lends and in-place slice sorting remain specification work; they are not available in the current execution backend. ## Why there are no lifetime annotations CP Lang does not ask you to name how long references live. It restricts where a borrow can go instead. A lent value may be a local `let`, an argument, a use inside one expression, or a loop's temporary value. It cannot escape into an owning field, a container, a `var`, a stored closure, or an ordinary return value. The implementation model is an inlined callback (there is no `inline` keyword; `lends`, `yield`, and closure arguments carry that contract): a projection runs the caller's use of the lent place while the owner is still available. Binding a lend to `let` puts the rest of that block inside the callback. The checker can see the whole use; there is no returned reference whose lifetime must be related to some other reference. That is the tradeoff, not a promise that arbitrary Rust borrowing works without annotations. Structures that must remember identity use plain indices or `List.push_id` handles. Functions that find a useful sub-range return a `Range`, then the caller reopens `a[span]` when needed. If you truly want independent storage, ask for `.copy()`. ```cp domain V = 1..=4 let a: [V]Int = [V] v => v.to_idx + 1 fn find_span(a: [V]Int) -> Range: V(1)..=V(4) let span: Range = find_span(a) // plain data: two boundaries let part = a[span] // a lexical lend, used here print(part.sum()) let saved = part.copy() // owned data may escape ``` `find_span` above is an ordinary user helper returning a range. It must not return a borrowed slice. Returning the recipe for access is simpler than returning access itself. ## Prove two accesses do not overlap The array's element projection declares this law: ```cp domain V = 1..=3 struct Counter: data: [V]Int fn at(mut self, i: V) -> lends mut Int: @law disjoint(i, j) = i != j mut self.data[i] var counter = Counter([V] v => 0) counter.at(V(3)) += 1 print(counter.data) ``` A trivial single-index forwarding projection like this one gets the `i != j` law automatically; it is written out here to show the contract. The law says when two lends through that same projection are separate. It does not assert that every call is safe. The checker must prove the condition at the call site. ```cp domain V = 1..=3 var counts: [V]Int = 1 let (i, j) = (V(1), V(3)) fn merge_into(mut dst: Int, src: Int): dst += src if i != j: merge_into(mut counts[i], counts[j]) ``` Without the guard or another proof of `i != j`, the two elements might alias, so a mutable access and a read cannot coexist. An explicit `assert i != j` is another way to establish the condition. Index arguments are evaluated before lending begins, so the proof is about fixed argument values, not indices that might change halfway through the call. For two ranges, the specified disjointness condition is that one ends before the other begins: `s.end <= t.start or t.end <= s.start`. Simultaneous mutable split-slice lends are not yet supported. Use independent owned workspaces today: ```cp let a = [4, 3, 2, 1] let mid = a.len / 2 var left: List = [] var right: List = [] for i in 0..mid: left.push(a[i]) for i in mid..a.len: right.push(a[i]) fn solve(mut left: List, mut right: List): left.sort() right.sort() solve(mut left, mut right) print(left, right) ``` The law applies to two calls of the **same projection** on the **same receiver**. Different operations do not automatically become disjoint: a row and a column may cross even when their arguments look different. ## Keep the owner obvious A lent row cannot be saved as the “best row so far” in a variable outside the loop. In the specified grid API, save its index and reopen the row later, or keep a deliberate copy. Generic row lends are not yet runnable; direct `grid[r, c]` access works today. A generator-lent value lasts for one iteration, not forever. These restrictions keep both mutation and performance visible at the use site. There are no user-visible pointer arithmetic tricks here. The intended primitive is a checked `Buffer.part`; arrays, slices, grids, and strings build their projections from it. An ordinary library can provide the same borrowing behavior as the standard one. --- # Cheat sheet URL: /docs/guides/cheatsheet Every block on this page is a complete program that runs. For the reasoning behind each line, read the [tour](/docs/guides/tour) or take the [course](/learn). ## Input The type says what to read. A range type is the statement's constraint: it is checked on input and picks the storage width. ```cp status=runs input="3 2\n1 2 3\nabc\ndef\nryan\n" let (n, q): (1..=2e5, 1..=2e5) = read() domain V = 1..=n let a: [V]1..=1e9 = read() let grid: [2, 3]Char = read() let name: Str = read() print(n, q, a.sum(), grid[0, 1], name) ``` | You write | It reads | | --- | --- | | `let n: 1..=2e5 = read()` | one integer, checked against the range | | `let (n, m): (Int, Int) = read()` | two integers | | `let a: [V]Int = read()` | one value per element of `V` | | `let g: [h, w]Char = read()` | `h` rows of `w` characters | | `let s: Str = read()` | one whitespace-separated token | | `@!multitest` | the number of test cases; the code below it runs once per case | ```cp status=runs input="2\n3\n1 5 2\n1\n7\n" @!multitest let n: 1..=100 = read() let a: [0..n]Int = read() print(a.max()! - a.min()!) ``` ## Output ```cp let xs = [3, 1, 4, 1, 5] let dist: [0..3]?Int = [0, None, 2] let ok = xs.len > 3 let x = 3.14159 print(xs) print(xs, sep: "\n") print(dist, none: "-1") print(yes(ok)) print("sum={xs.sum()} pi={x:.2f} n={xs.len:03}") ``` `print` puts spaces between arguments and ends the line. Lists and arrays print on one line. `yes(b)` turns a `Bool` into `YES` or `NO`; `print` does not take a bare `Bool`. ## Control flow, arithmetic and optionals ```cp var best: ?Int = None for x in [4, 9, 2]: best max= x print(best ?? -1) if let b = best: print(b + 1) var total = 0 for i in 0..5 if i % 2 == 0: total += i var k = 10 while k > 1: k /= 2 print(total, k, 7 / 2, -7 % 3, 2 ** 10, min(3, 5)) ``` - `0..n` excludes `n`; `0..=n` includes it. - `/` and `%` are Euclidean: `-7 % 3` is `2`. - Write `and`, `or`, `not`, and `elif`. - `?T` is a `T` or `None`. `??` gives a fallback, `x!` unwraps, `if let` binds, and `min=` / `max=` skip `None`. ## Arrays, domains and sequences ```cp let a = [5, 2, 8, 2] print(a.sum(), a.min()!, a.max()!, a.sorted(), a.count(x => x == 2)) print(yes(a.any(x => x > 7)), yes(a.all(x => x > 1))) print(sum(x * x for x in a), [x for x in a if x % 2 == 0]) domain V = 1..=4 let b: [V]Int = [V] v => v.to_idx * 10 for v in V: print(v, b[v], end: " ") print() ``` - `domain V = 1..=n` names an index space. `[V]T` is an array over it, and `a[v]` needs a `V`. - `V(3)` makes an index from an integer; `v.to_idx` goes back to a 0-based integer. - `a.min()` and `a.max()` return `?T`, because the sequence may be empty. ## Collections ```cp var xs: List = [] xs.push(5) xs.push(2) xs.push(8) let ys = xs.sorted() print(ys, ys.rev, xs.pop() ?? 0) var seen: Set = Set() seen.add(3) var cnt: Map = Map() cnt[7] += 1 cnt[7] += 1 print(yes(3 in seen), cnt[7]) var h = MinHeap() h.push(4) h.push(1) print(h.pop() ?? -1) ``` ## Functions, records and enums ```cp type P = (x: Int, y: Int) fn norm(p: P) -> Int = p.x * p.x + p.y * p.y fn bump(mut a: [0..3]Int, i: 0..3): a[i] += 1 var a: [0..3]Int = 0 bump(mut a, 1) enum Op: Add(k: Int) Clear fn apply(x: Int, op: Op) -> Int: match op: Add(k) => x + k Clear => 0 print(norm((x: 3, y: 4)), a, apply(5, Add(2)), apply(5, Clear)) ``` A function that changes an argument takes it as `mut`, and the caller writes `mut` too. ## Tools | Command | What it does | | --- | --- | | `cpl run a.cp` | run with the interpreter, reading stdin | | `cpl check a.cp` | type-check only | | `cpl build a.cp -o a.cpp` | write one C++17 file to submit | | `cpl run a.cp --trace` | record the run to `a.trace.html`, the time-step viewer | | `cpl stress a.cp` | compare against `@alt` on random inputs and shrink the first failure | The [playground](/play) has the same Run, Trace and Stress buttons. See the [stress guide](/docs/guides/stress) and the [CLI reference](/tools). --- # From C++17 & performance URL: /docs/guides/cpp-guide If you already solve contest problems in C++17, you already know every algorithm you need. This guide shows how to **rethink** C++17 contest solutions into idiomatic CP Lang — at the gold standard of `design/EXEMPLARS-PORTS.md` — where the editorial invariant reads top-to-bottom, each bound and modulus is written once, and `cpl build` emits fast, judge-ready C++17. ## Rethink, don't translate Compare how a Codeforces Div2 C (`cf2069c`, Beautiful Sequence: count `1 2…2 3` subsequences mod `998244353`) reads in C++17 vs CP Lang: ```cpp C++17 int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); int T; cin >> T; while (T--) { int N; cin >> N; using num = modnum<998244353>; num dp = 0, ans = 0, empty = 0; for (int i = 0; i < N; i++) { int a; cin >> a; if (a == 1) { dp++; empty++; } else if (a == 2) { dp += dp; } else if (a == 3) { ans += dp - empty; } } cout << ans << '\n'; } } ``` ```cp // A beautiful subsequence is 1 2...2 3 with at least one 2. // Track subsequences ending in "1" and those ending in "1 2+". type Z = Mod<998_244_353> let xs: List = [1, 2, 1, 2, 3] var ones: Z = 0 var open: Z = 0 var ans: Z = 0 for a in xs: match a: 1 => ones += 1 2 => open = 2 * open + ones 3 => ans += open _ => continue print(ans) ``` Notice what disappeared: `ios_base::sync_with_stdio`, manual `while (T--)` (replaced by `@!multitest` at file top), `#define int long long` (`Int` is always 64-bit), and the `dp - empty` mental arithmetic trick. ## Everyday C++17 habits → CP Lang | C++17 habit | Idiomatic CP Lang | Why | | --- | --- | --- | | `ios::sync_with_stdio(false); cin.tie(nullptr);` | Automatic | Fast buffered I/O is always on; `flush()` flushes interactive prompts. | | `int T; cin >> T; while (T--) solve();` | `@!multitest` | Precomputation above `@!multitest` runs once; per-test state and `@memo` caches reset automatically. | | `int n; cin >> n; vector a(n + 1);` | `let n: 1..=2e5 = read()` / `domain V = 1..=n` / `let a: [V]Int = read()` | Bounds are declared once and eliminate off-by-one and cross-index bugs. | | `const long long INF = 1e18; dist[v] = min(dist[v], d);` | `var dist: [V]?Int = none` / `dist[v] min= d` | Niche-packed `?Int` uses `INT64_MIN` (0 extra bytes) and prevents `INF + w` overflow. | | `((a % m) + m) % m` | `a % m` | `%` is Euclidean (`0 <= a % m < m`) for all integers. | | `dx[4] / dy[4]` + bounds check | `type Cell = (Row, Col)` + `for q in p.adj4:` | Grid neighbors are guaranteed in-bounds without manual `0 <= nx && nx < h`. | | `sort(a.begin(), a.end(), cmp)` | `a.sort(by: x => (x.r, desc(x.l)))` | Key functions compose tuples and `desc(...)` without writing strict-weak-order structs. | | `priority_queue, greater>` | `MinHeap` / `MaxHeap` | Direction is explicit in the type name. | | `multiset::erase(s.find(x))` | `bag.remove_one(x)` | Never accidentally deletes all duplicates of `x`. | | `vector> adj[n]` | `Graph.undirected(...)` or `var adj: [V]List = []` | `Graph` lowers to a flat CSR array; `[V]List` is indexed strictly by `V`. | | `for (auto [u, v] : edges) { g[u].push_back(v); g[v].push_back(u); }` | `for (a, b) in [(u, v), (v, u)]:` or `Graph.undirected(...)` | One edge fact in one place (lint `L0503` catches duplicated symmetric writes). | | `bool ok = false; for (...) if (p) { ok = true; break; }` | `let ok = xs.any(p)` | Express search intent directly (lint `L0501` catches flag-and-break loops). | ## Sentinels and relaxation without `INF` In C++, `INF = 1e18` is a constant source of `INF + w` overflow and forgotten `if (dist[u] == INF) continue;` guards. In CP Lang, `?Int` with `min=` / `max=` handles absence natively: ```cp domain V = 1..=4 var dist: [V]?Int = none dist[V(1)] = 0 for (u, v, w) in [(V(1), V(2), 5), (V(2), V(4), 3), (V(1), V(4), 10)]: if let d = dist[u]: dist[v] min= d + w print(dist[V(4)] ?? -1) ``` ## Named invariants instead of parallel arrays When a C++ solution keeps three parallel vectors (`stk_len`, `stk_val`, `offset`) or a raw segment-tree node array in sync by hand, give the invariant a `struct` and a combining function: ```cp // Maximum subarray sum monoid: no fake sentinels, one combining rule. struct Seg(total: Int, pref: Int, suff: Int, best: Int) fn combine(a: Seg, b: Seg) -> Seg: Seg( total: a.total + b.total, pref: max(a.pref, a.total + b.pref), suff: max(b.suff, b.total + a.suff), best: max(max(a.best, b.best), a.suff + b.pref), ) let x = combine(Seg(3, 3, 3, 3), Seg(-1, 0, 0, 0)) let y = combine(x, Seg(4, 4, 4, 4)) print(y.best) ``` ## What `cpl build` emits `cpl build solve.cp -o solve.cpp` produces a single, self-contained, human-readable C++17 file for the target judge profile: - **Original `.cp` source included as a header comment** at the top of the `.cpp` file so judges and reviewers always see the clean source. - **Tree-shaken standard and local libraries:** only reachable data structures and helpers are emitted; `@alt`, `@check`, `@interactor`, `@gen`, `@test`, and `@law` blocks are stripped so submissions stay well under 64 KB. - **Zero-cost domains and indices:** `domain V = 1..=n` erases to a plain `int32_t` index; `[V]T` lowers to a contiguous flat `std::vector` with zero bounds checks on valid `V` accesses. - **Niche-packed optionals:** `?Int` (`INT64_MIN`), `?F64` (quiet `NaN`), `?V`, `?Bool`, `?Char`, and `?Enum` take zero extra bytes — no `std::optional` padding overhead. - **Compact `Mod

`:** stored as a 4-byte `uint32_t` with compile-time modulus reduction when `P` is `const`. - **Flat CSR graphs:** `Graph` packs adjacency lists into two contiguous arrays (`head` + `edges`) rather than `vector>`, avoiding heap fragmentation and pointer chasing. - **Salted hash maps:** `HashMap` uses splitmix64 with a runtime-seeded salt to resist predictable anti-hash tests. - **Smart `@memo` lowering:** state spaces up to `2^24` entries lower to a flat contiguous table; larger spaces fall back automatically to a salted hash map. ## Judge profiles `cpl build` targets one named judge profile: `generic` (default), `codeforces`, `atcoder`, `cses`, `icpc` (DOMjudge), `kattis`, or `dmoj`. Each profile fixes compiler flags, platform, stack size, and source-size limit. `cpl judges` lists all profiles and marks the active one. Selection order (first match wins): - `cpl build a.cp --judge atcoder` - a `// judge: atcoder` comment in the file - `judge = "atcoder"` under `[judge]` in the nearest `cp.toml` Custom profiles in `cp.toml` can extend a built-in judge: ```toml [judge] judge = "school" [judge.school] extends = "icpc" stack_mb = 64 # or "unlimited" source_kb = 100 flags = ["-std=c++17", "-O2"] int128 = false # `I128` becomes a build error naming the judge ``` What the profile changes in the file: the header names the judge and its command; the program runs on a thread with the profile's thread stack (1 GB unless `thread_stack_mb` says otherwise; with `thread_stack_mb = 0`, for a judge that allows no threads, `main` runs it and `cpl build` warns); the source limit is the judge's, with a warning past three quarters of it and the C++'s own comments left out (then the source header, then half the indentation) only when the file would not fit otherwise. `cpl build` prints the file's size as a share of that limit. `cpl run --release`, `cpl test` and `cpl stress` build the same C++ with the judge's flags (those the compiler here accepts) and run it on the judge's stack. `cpl submit a.cp` does both in one step: it writes the C++ as `cpl build` does, runs every case in `a.tests/` on it as `cpl test` does, and exits 0 only when the file is ready to send. ## Performance controls and escape hatches Clean high-level CP Lang matches hand-written `g++ -O2` C++17 within a narrow margin, and provides explicit escape hatches whenever a tight time limit demands raw control: - **Plain integer indexing:** use structural range arrays such as `[0..n]Int` when an algorithm needs numeric offsets. - **`unchecked:` block:** opt out of local overflow and bounds checks inside an inner hot loop you have already proved safe: ```cp let n = 3 let a: [0..n]Int = 2 let b: [0..n]Int = 3 var acc = 0 unchecked: for i in 0..n: acc += a[i] * b[i] print(acc) ``` - **`O(1)` cleared arrays (`std.marks.Marks`):** in multi-query algorithms where each query touches a few indices, use `Marks` (32-bit generation stamp) or a touched-list instead of `a.fill(false)`. - **Explicit iterative DP:** when a tight 2D DP needs a rolling 1D buffer for cache locality or memory limits, write the iterative loop directly with `[0..=cap]Int` — `@memo` is optional. - **Inspect the C++17 anytime:** click **C++17** in the [playground](/play) or run `cpl build solve.cp` locally to verify the exact loop and memory layout `g++ -O2` will compile. --- # Getting started & CLI URL: /docs/guides/getting-started You can try CP Lang immediately with zero setup in the [browser playground](/play), or install the local `cpl` CLI to run programs natively, emit standalone C++17 for online judges, and enable editor support (`cpl lsp`). ## Install From the first release, one line installs a prebuilt binary. That release is not out yet, so this command does not work today: ```sh curl -fsSL https://cp-lang.org/install.sh | sh # latest stable release curl -fsSL https://cp-lang.org/install.sh | sh -s -- --edge # newest build of main that passed every check ``` Until then, build `cpl` with Rust. It compiles CP Lang programs to standard C++17 (any `g++` or `clang++` that supports `-std=c++17`). ```sh cargo install --locked --git https://github.com/ryanbai1412/cp-lang cpl-cli ``` Verify the installation: ```sh cpl --version cpl --help ``` ## Write, run, and compile your first program Save this example as `sum.cp`: ```cp let n: 1..=2e5 = read() domain V = 1..=n let a: [V]Int = read() print(a.sum()) ``` Check types, run directly with the local interpreter, or compile to a standalone C++17 submission: ```sh cpl check sum.cp printf '5\n3 1 4 1 5\n' | cpl run sum.cp cpl build sum.cp -o sum.cpp g++ -std=c++17 -O2 sum.cpp -o sum printf '5\n3 1 4 1 5\n' | ./sum ``` The output is `14`. `cpl build` writes a single self-contained `.cpp` file with your original `.cp` source preserved as a comment header at the top, unused library code tree-shaken away, and `@alt` / `@check` / `@interactor` blocks stripped so the file is clean and ready to upload to any judge. ## Editor support (`cpl lsp`) The `cpl` CLI ships with a built-in Language Server Protocol server (`cpl lsp`) powered by the same incremental frontend as `cpl check`. Point your editor's LSP client at `cpl lsp` for real-time diagnostics, hover types, and completion while writing `.cp` files. ## What works today CP Lang is in beta. `cpl check`, `cpl run`, `cpl build`, `cpl stress`, `cpl lsp` and the trace viewer all work, in the CLI and in the browser. Parts of the standard library are still being implemented: an example on this site marked **check-only** passes the type checker but does not run yet. Next: the [course for your language](/learn), the [cheat sheet](/docs/guides/cheatsheet), the [language tour](/docs/guides/tour), or the [C++17 migration guide](/docs/guides/cpp-guide). --- # Idioms URL: /docs/guides/idioms Gold-standard CP Lang solutions read like the editorial: the header states the invariant in two to five lines, each index space has one `domain`, each bound or modulus is written once, and standard structures are named rather than re-derived inline. Every snippet below is checked by `cpl check` and `cpl build` in the gate. ## 1. One fact in one place: bounds, domains, and moduli Write every constraint and modulus once at the top of the solution (`const`, `type Z = Mod<...>`, `domain`), then let types carry bounds through every array and loop: ```cp const LIM = 200_000 type Z = Mod<998_244_353> let n = 5 domain V = 1..=n let a: [V]Int = [1, 2, 3, 4, 5] var total: Z = 0 for v in V: total += a[v] print(total) ``` When a problem has two distinct index spaces (items vs cuts, rows vs columns, vertices vs edges), give each its own `domain` so swapping them is a compile-time error (`E0301`), not a silent WA: ```cp domain Item = 1..=3 domain Cut = 0..=3 let weight: [Item]Int = [4, 7, 2] var pref: [Cut]Int = 0 for i in Item: let k = i.ord pref[Cut(k + 1)] = pref[Cut(k)] + weight[i] print(pref[Cut(3)]) ``` ## 2. Searches and reductions instead of flag loops Prefer `any`, `all`, `sum`, `count`, `min`, and `max` over manual boolean flags and accumulator loops (enforced by lints `L0501`, `L0504`, `L0505`): ```cp let xs: List = [3, 8, 2, 9, 5] let has_big = xs.any(x => x > 7) let all_pos = xs.all(x => x > 0) let evens = xs.count(x => x % 2 == 0) let total = sum(x for x in xs) print(yes(has_big), yes(all_pos), evens, total) ``` Use `for x in xs if cond:` to filter cleanly without extra nesting, and `xs.adjacent` / `zip` / `enumerate` instead of `for i in 0..xs.len:`: ```cp let xs: List = [2, 5, 4, 9] let asc = xs.adjacent.count(p => p.0 < p.1) let pos_sum = sum(x for x in xs if x >= 4) print(asc, pos_sum) ``` ## 3. Zero-sentinel optionals (`?T`) and `min=` / `max=` Never invent `-1` or `1e18` sentinels, and never initialize `var best = 0` before `best min= x` (since `0` would stay smaller than any positive value). Use `?Int` with `min=` / `max=`, `if let`, `??`, and early-return `let x = opt ?? return`: ```cp fn best_even(xs: List) -> ?Int: var best: ?Int = none for x in xs if x % 2 == 0: best max= x best print(best_even([1, 3, 5]) ?? -1) print(best_even([1, 4, 9, 2]) ?? -1) ``` ## 4. Grids without `dx` / `dy` boilerplate Model grid coordinates as `(Row, Col)`. Every cell automatically exposes in-bounds `.adj4` and `.adj8` neighbors with zero manual bounds checks: ```cp let (h, w) = (2, 3) domain Row = 0..h domain Col = 0..w var deg = 0 for r in Row: for c in Col: for (nr, nc) in (r, c).adj4: deg += 1 print(deg) ``` ## 5. Sorting, heaps, bags, and frequency tables Use key functions with `desc(...)` for multi-key sorting, `MinHeap` / `MaxHeap` for priority queues, `SortedBag` for multisets (`remove_one`), and `HashMap` where `m[k]` returns `V` directly (auto-inserting the default on miss — never apply `??` or `!` to `m[k]`) while `m.get(k)` returns `?V`: ```cp var pts: List<(Int, Int)> = [(2, 5), (1, 3), (2, 1)] pts.sort(by: p => (p.0, desc(p.1))) var freq: HashMap = HashMap() for (x, _) in pts: freq[x] += 1 var h: MinHeap = MinHeap() for x in [7, 2, 9]: h.push(x) print(pts[0].0, pts[0].1, freq[2], h.pop() ?? -1) ``` ## 6. Binary search and prefix sums Use integer binary search on a monotone predicate with explicit `lo`/`hi` invariants, or `lower_bound` / `upper_bound` on sorted lists: ```cp // First x in 1..=100 whose square is at least 50. var lo = 1 var hi = 100 while lo < hi: let mid = lo + (hi - lo) / 2 if mid * mid >= 50: hi = mid else: lo = mid + 1 print(lo) ``` ## 7. Standard data structures: DSU, Fenwick, and Segment Trees Import battle-tested data structures from `std.*` instead of re-deriving them inline: ```cp status=checks use std.dsu.Dsu use std.fenwick.Fenwick domain V = 1..=4 var dsu = Dsu() let _ = dsu.unite(V(1), V(2)) let _ = dsu.unite(V(2), V(3)) var bit = Fenwick() bit.add(V(1), 5) bit.add(V(3), 7) print(yes(dsu.same(V(1), V(3))), yes(dsu.same(V(1), V(4))), bit.prefix(V(3).r)) ``` ## 8. Quick idiom reference Every block below is a complete program checked by the compiler when this site is built. ### Read `n` and a 1-based array Name the index space once; the array, its loops and its queries all use it. ```cp input="3\n5 6 7\n" let n: 1..=2e5 = read() domain V = 1..=n let a: [V]Int = read() print(a[V(1)], a.sum()) ``` ### `[0..n]` or `[0..=n]` `[0..n]T` has `n` cells; `[0..=n]T` has `n + 1`, so use it when `n` itself is a DP state. `sorted()` returns a 0-indexed list. ```cp let n = 4 var count: [0..n]Int = 0 var dp: [0..=n]Int = 0 dp[n] = 1 let sorted = [3, 1, 2].sorted() print(count.len, dp.len, sorted[0]) ``` ### Strings and characters A `Str` is ASCII: `s[i]` is a `Char`, and `c - 'a'` is an `Int`. Compare characters with two comparisons. A slice is a view; `.to_str()` copies it when it must outlive the string or be appended. ```cp input="banana\n" let s: Str = read() let c = s[0] fn head(s: Str, k: Int) -> Str: s[..k].to_str() var out = "" out += s[2..4].to_str() print(s.len, yes('a' <= c and c <= 'z'), c - 'a', head(s, 3), out) ``` ### Printing `print` separates arguments with a space and ends the line; `end:` and `sep:` change that. A `[D]Char` prints as one word. Interpolate with `"{n}"`. ```cp input="abc\n" let chars: [3]Char = read() let n = 4096 print(chars) print(chars, sep: " ") for x in [1, 2, 3]: print(x, end: " ") print() print("{n}".len, n.digits()) ``` ### YES and NO `print` does not take a `Bool`. `yes(ok)` gives `YES` or `NO`; `with io(answers: ...)` changes the words for a scope, and `answers:` for one call. ```cp let ok = 3 > 2 print(yes(ok)) with io(answers: ("Yes", "No")): print(yes(ok)) print(yes(ok, answers: ("Possible", "Impossible"))) ``` ### Maps `m[k] += 1` starts an absent key from zero. Reading an absent `m[k]` traps (`R0001`), so read with `m.get(k)`, which is optional. `??=` fills an absent entry and hands it back. ```cp var cnt: Map = Map() cnt[7] += 1 cnt[7] += 1 var groups: Map> = Map() (groups[1] ??= Set()).add(5) print(cnt[7], cnt.get(8) ?? 0, groups[1].len) ``` ### Grids One pair of brackets, comma-separated indices. ```cp var g: [2, 3]Int = 0 g[1, 2] = 5 print(g[1, 2]) ``` ### Modular arithmetic The modulus is part of the type. `**` is power and `.inv` is the inverse. ```cp type Z = Mod<998244353> let z = Z(3) print(z, z ** 2, z.inv * z) ``` ### Swap, reverse, adjacent pairs Swap with a tuple assignment. `reverse()` works in place; `.rev` iterates backwards. ```cp var (a, b) = (1, 2) (a, b) = (b, a) var xs = [1, 4, 9] (xs[0], xs[2]) = (xs[2], xs[0]) xs.reverse() for (p, q) in xs.adjacent: print(q - p, end: " ") for i in (0..3).rev: print(i, end: " ") print(a, b) ``` ### Clearing between tests `fill` resets an array in place. ```cp var a: [0..4]Int = 7 var seen: [0..4]?Int = None seen[1] = 3 a.fill(0) seen.fill(None) print(a, seen[1] ?? -1) ``` ### `mut` parameters A function that changes its argument says `mut`, and so does the caller. To change a value locally, copy it into a `var`. ```cp fn bump(mut x: Int): x += 1 fn twice(x: Int) -> Int: var cur = x cur *= 2 cur var v = 1 bump(mut v) print(v, twice(v)) ``` ### Long expressions and `match` Break a line inside parentheses. A `match` arm is `pattern => expression`. ```cp let total = (1 + 2 + 3) let kind = 2 let name = match kind: 1 => "one" _ => "many" print(total, name, abs(-3), min(2, 5), max(2, 5), gcd(12, 18), lcm(4, 6)) ``` ### Multiple test cases `@!multitest` reads the count and runs the rest of the file once per test. `return` ends the current test. ```cp input="2\n1\n5\n" @!multitest let n: 1..=100 = read() if n == 1: print(0) return print(n * 2) ``` ### Stress test against a brute force Mark the slow version `@alt(main)` in the same file and run `cpl stress`. Inputs are generated from the types at `read`. ```cp input="3\n4 9 2\n" let n: 1..=8 = read() let a: [n]1..=20 = read() print(a.max()!) @alt(main) fn slow(): var best = 0 for x in a: best max= x print(best) ``` --- # Index spaces, domains & slices URL: /docs/guides/indices Most off-by-one bugs come from storing two kinds of numbers in the same `int`: an element position, a gap between elements, a count, or a vertex from a different graph. CP Lang separates them with two complementary tools: **structural range arrays** `[0..n]T` / `[0..=k]T` for quick integer-indexed tables, and **nominal domains** `domain V = 1..=n` when you want compile-time separation between index spaces. ## Structural range arrays (`[0..n]T`, `[0..=k]T`) When an array is just a scratch table indexed by plain integers—like a frequency count or digit bucket—you do not need to name a domain: ```cp let n: 0..=100 = read() let k: 0..=100 = read() let a: [0..n]0..=k = read() var cnt: [0..=k]Int = 0 for i in 0..n: cnt[a[i]] += 1 cnt.fill(0) // reset the whole array in place ``` Structural range arrays unify across functions whenever their written bounds match (`[0..n]Int` matches `[0..n]Int`). Index an array using the **same bounds** it was declared with (`for i in 1..=n:` for `[1..=n]T`, `for i in 0..n:` for `[0..n]T`; indexing `[1..=n]T` at `0` traps at runtime). `for i in 0..n` binds `i: Int`, so `i + 1` is `Int`. Nominal domain values (`v: V`) are **not** `Int`: you cannot multiply or pass `v` where `Int` is expected, nor index `[V]T` with an `Int` — convert explicitly with `v.ord` / `v.to_idx` (to `Int`) or `V(k)` (from `Int`), or use a structural range array `[0..n]T` / `[1..=n]T` when you need integer arithmetic on indices. Generic stdlib structures (`Dsu`, `DsuOf`, `Fenwick`, `SegTree`, `Graph`) require a **named `domain V = ...`**, never an inline range like `Dsu<1..=n>`. Neighbor properties `v.next` / `v.prev` and domain arithmetic `v + 1` / `v - 1` / `V.last - 1` return `?V` (they may step outside the domain — unwrap with `if let nxt = v.next:` or `??` before indexing or forming a range). Multi-dimensional `[R, C]T` arrays take comma-separated indices (`g[r, c]`) and accept a scalar fill (`var g: [R, C]T = 0`), whereas nested `[R][C]T` is an array of arrays and `[R]List` is indexed as `adj[r][k]`. Unnamed grid cell tuples `(r, c): (Row, Col)` (not named records `(r: Row, c: Col)`) have built-in `.adj4` and `.adj8` neighbor properties without importing anything. Use `a.fill(x)` (or `seen.fill(none)` on `[D]?T`) to clear an array between test cases. ## Nominal domains and `Index` Declare a nominal domain with `domain Name = lo..=hi` (or counted shorthand `domain Name = n`, which means `0..n`) whenever you want zero-check indexing and compile-time protection against mixing different index spaces: ```cp let n = read(1..=2e5) let m = read(1..=2e5) domain Row = 1..=n domain Col = 1..=m domain Bucket = 10 // counted domain: same as 0..10 print(Row.count, Bucket.count) ``` `Row` and `Col` are distinct types even when `n == m`. An array `[Row, Col]Int` accepts `(r, c)` in that order only; swapping `r` and `c` is a type error before the program runs. ```cp let n: 1..=2e5 = read() domain V = 1..=n let a: [V]Int = read() print(a.sum()) ``` A domain implements the `Index` and `Seq` traits: - `V.count` (and `V.K`) is the number of elements; `V.first` and `V.last` are the endpoints as `?V` (`none` for an empty domain; unwrap with `!`). - `v.to_idx` converts to `0..V.count` and `V.from_idx(i) -> ?V` converts back safely. - `v + k -> ?V` and `v - k -> ?V` step by an integer offset and return `none` past the ends; `b - a -> Int` is the signed distance; `v.cyc(k) -> V` wraps cyclically. - Step along a named domain in either direction with `for v in V by k:` and `for v in V.rev by k:`. Array endpoints are **values**, not domain indices: `a.first` and `a.last` return `?T`, while `V.first` and `V.last` are optional indices. Like lists, empty arrays return `none`; unwrap with `a.first!` or `a.last!` only when nonempty. An unwrapped endpoint is also a mutable place, so `a.last! += 1` works on a mutable array or list: ```cp domain V = 5..8 let a: [V]Int = [V] v => 10 + v.to_idx let endpoints: (?Int, ?Int) = (a.first, a.last) print(V.first, V.last, endpoints.0!, endpoints.1!) // 5 7 10 12 domain Empty = 0..0 let empty: [Empty]Int = 0 print(empty.first ?? -1, empty.last ?? -1) // -1 -1 ``` ## Boundaries: `.l` and `.r` Prefix sums, difference arrays, and knapsack tables live on the `n + 1` gaps around `n` elements. Every ordered domain `V` has a companion boundary space `V.cuts` with `V.K + 1` positions. ```cp let n: 1..=100 = read() domain V = 1..=n let a: [V]Int = read() var pre: [V.cuts]Int = 0 for v in V: pre[v.r] = pre[v.l] + a[v] print(pre[V.last!.r]) ``` Every element `v: V` sits between two boundaries: - `v.l` is the gap immediately to the left of `v`; `v.r` is the gap immediately to the right of `v`. - `v.l(k)` and `v.r(k)` jump to the `k`-element window boundaries counting `v` (`v.l == v.l(1)`, `v.r == v.r(1)`). - `b.left -> ?V` and `b.right -> ?V` move from a boundary back to the adjacent element. The same `.l`/`.r` notation works directly in multi-dimensional DP tables such as 0/1 knapsack (`[I.cuts, 0..=cap]Int`): ```cp let n: 1..=50 = read() let cap: 1..=1000 = read() domain I = 1..=n let items: [I](w: 1..=1000, v: 0..=1e9) = read() var best: [I.cuts, 0..=cap]Int = 0 for i in I: for c in 0..=cap: best[i.r, c] = best[i.l, c] if c >= items[i].w: best[i.r, c] max= best[i.l, c - items[i].w] + items[i].v print(best[I.last!.r, cap]) ``` ## Ranges, open ends, and slices One `Range` type covers half-open `l..r`, inclusive `l..=r`, and open-ended `..i`, `..=i`, `i..`, `i.r..`, and `l.r..r.l` (strictly between `l` and `r`). Every range provides `.first -> ?I`, `.last -> ?I`, `.mid -> ?I`, `.len`, `.is_empty`, `.rev`, `.step(k)`, and `(lo..=hi).clamp(D)`; `Range.sum()` and `(a..b).step(k).sum()` are O(1) closed forms. Range data structures accept range arguments such as `st.fold(..h[i])` and `pre.fold(..i)`. Array slices use the array's own index base (`a[2..=4]` on a `[1..=4]Int` is its last three cells), and grid slices `g[r, ..]` / `g[.., c]` act as 1-D `[D]T` arrays that can be passed directly to generic functions such as `sum` and `argmax`. In-place slice mutation remains specification work; use the explicit copy-and-writeback example when sorting a window. ```cp let one: [1..=4]Int = [10, 20, 30, 40] print(one[2..=4].sum()) // 90 (1-based slice) let g: [1..=2, 1..=3]Int = [[1, 5, 2], [4, 3, 6]] print(argmax(g[.., 3])!) // 2 (row index along the 1..=2 axis) ``` An open-ended `Int` range `l..` also works in a loop. Unlike an open-ended slice, it has no container to supply its endpoint: stop explicitly rather than trying to collect an unbounded iteration. ```cp let l = 3 for i in l..: if i == 6: break print(i) // 3, then 4, then 5 ``` ## Grids and `Cell = (Row, Col)` A 2D array `[Row, Col]T` uses row and column domains. The example below names their pair `Cell`, iterates the two domains separately, and indexes `g[r, c]`. Product-domain iteration and fully generic cell-indexed structures are still being completed. ```cp use std.grid.{adj4} let h: 1..=50 = read() let w: 1..=50 = read() domain Row = 1..=h domain Col = 1..=w type Cell = (Row, Col) let g: [Row, Col]Char = read() fn visit(p: Cell): print(p) for r in Row: for c in Col: let p: Cell = (r, c) for q in p.adj4: if g[q.0, q.1] != '#': visit(q) ``` The imported `p.adj4` yields in-bounds orthogonal neighbors. `std.grid` also declares `adj8`, `step`, `ray`, and `Dir4`. Generic row/column lends and transformed grid views remain specification work rather than runnable APIs. ## Coordinate compression with `compress(all)` Coordinate compression produces a fresh nominal domain `xs.D` together with value lookup and inverse mapping: ```cp status=spec let all_coords = [30, 10, 20] let queries = [10, 30] let xs = compress(all_coords) var bit = Fenwick() var ans = 0 for x in queries: let id = xs.at(x) // exact lookup -> xs.D let original = xs[id] // original value at id bit.add(id, 1) if let ge = xs.first_ge(x): // lower bound -> ?xs.D ans += bit.prefix(ge.l) print(ans) ``` You never accidentally pass an uncompressed value into `bit` or mix a compressed index with raw coordinates. ## Fresh runtime domains and existential returns A domain can be declared from any runtime expression that yields a count, a range, a sequence, or another domain — including `domain V = read(1..=n)` and `domain C = compress(xs)`. Each declaration site owns one runtime slot (saved and restored automatically across recursive calls), and runtime-sized arrays live on the heap rather than the stack. A fresh domain cannot escape the block or function that declares it (`E0313`) unless the function exposes it explicitly in an existential return type: ```cp fn make_seq(k: Int) -> (domain P, [P]Int): domain Local = 0..k (Local, [Local] i => i.to_idx * 2) let (domain Q, vals) = make_seq(4) print(Q.count, vals.sum()) ``` Standard-library functions that introduce a new index space (`components`, `scc`, `two_edge_components`) use the same pattern: `let (domain C, comp) = scc(adj)`. Record types read by `read()` may also bound fields by earlier runtime values, e.g. `let edges: [0..m](u: V, v: V, w: 0..=m) = read()`. ## Symmetric tables and domain iteration helpers For undirected adjacency matrices and other symmetric relations over a domain `V`, `[Sym]T` stores unordered pairs in a flat triangular array of `n * (n + 1) / 2` cells where `adj[u, v]` and `adj[v, u]` refer to the same entry. Domains also provide typed slicing and unordered pair iteration (`V.after(i)`, `V.before(i)`, `V.pairs`, and `domain P = V.pairs`): ```cp domain V = 1..=4 var adj: [Sym]Bool = false adj[V(1), V(3)] = true var missing = 0 for (i, j) in V.pairs if not adj[i, j]: missing += 1 var after_first = 0 for j in V.after(V(1)): after_first += 1 print(yes(adj[V(3), V(1)]), missing, after_first) ``` `for (i, j) in V.pairs` and `for j in V.after(i)` / `V.before(i)` lower directly to nested integer loops with no intermediate allocation. ## Domain subsets, enum-indexed tables, and sequence operations Domains compose directly with bitsets (`V.all`, `Bitset`, `adjacency(edges, into: Bitset)`), fieldless enums (`[Sign]T` and `[Sign] x => ...`), domain-typed sequence operations (`partition`, `sort(by:)`, `group(by:)`, `at`, `first(p)`), and paired `Item`/`Cut` ranges via `minmax`: ```cp enum Sign: neg = -1, zero = 0, pos = 1 let vals: [Sign]Int = [Sign] s => Int(s) * 10 domain V = 1..=4 let edges: List<(u: V, v: V)> = [(V(1), V(2)), (V(2), V(3))] let adj = adjacency(edges, into: Bitset) let rest = V.all - adj[V(2)] let (evens, odds) = V.partition(v => Int(v) % 2 == 0) let first_big = V.first(v => Int(v) > 2) print(vals[Sign.neg], rest.len, evens.len, odds.len, first_big!) ``` Range structures (`SegTree`, `Fenwick`) also accept `V.cuts` directly as their index domain, so boundary updates (`seg.set(v.r, x)`, `seg.apply(..=v.l, 1)`) need no shadow `0..=n` domain. For divide-and-conquer over any `Range`, `let (left, right) = r.halves()` splits `r` in O(1) with both halves non-empty whenever `r.len >= 2`. ### Product domains A Cartesian product of finite domains (including fieldless enums and `Bool`) can be named as one flat domain with `domain State = (V, K)` or named factors `domain State = (v: V, ok: Bool)`. Values pack in row-major order into a single `0..len(V) * len(K)` slot, so `[State]T` is a flat array, `for s in State:` and `for (v, k) in State:` iterate every state, and `dp[(v, k)]`, `dp[v, k]`, and `dp[State(v, k)]` all index it while rejecting swapped factor order with `E0301`: ```cp domain V = 0..3 domain K = 1..=2 domain State = (V, K) var dp: [State]Int = 0 for (v, k) in State: dp[(v, k)] = v.ord * 10 + k.label let s = State(V(2), K(1)) print(dp[s], dp[V(2), K(2)], s.0.ord, State.len) ``` ## Inverting bijections and partial injections `a.inverse()` inverts any 1D array whose elements are an index domain, fieldless enum, or bounded integer range. On a total bijection `a: [D]E` it returns `[E]D` (trapping if a value is repeated or missing); on a partial injection `a: [D]?E` it returns `[E]?D` (trapping if two positions map to the same value): ```cp domain P = 1..=4 var a: [P]?(1..=4) = none a[P(2)] = 4 a[P(4)] = 1 let at = a.inverse() print(at[1]!.label, yes(at[2] == none), at[4]!.label) ``` ## Algebraic `Index` and escape hatches The language's `Index` model (§2.16) covers `Bool`, finite enums (both fieldless and payload enums whose fields are index types), `?T`, integer ranges, tuples/records of index types, and `Subset` for bitmask DP. Payload enums such as `enum Node: Src / Snk / Cell(Row, Col)` and tuples/records such as `(Row, Col)` work directly as array dimensions (`[Node]T`, `[(Row, Col)]T`), loop domains (`for v in Node:`), and generic index arguments (`FlowGraph`, `FlowGraph<(Row, Col)>`, `Dsu`): ```cp use std.flow.{FlowGraph} domain Row = 0..2 domain Col = 0..3 enum Node: Src Snk Cell(Row, Col) var g = FlowGraph() g.add(Node.Src, Node.Cell(Row(0), Col(0)), 4) g.add(Node.Cell(Row(0), Col(0)), Node.Snk, 3) print(Node.count, g.max_flow(Node.Src, Node.Snk)) ``` For numeric offsets, use a structural range array such as `[0..n]Int`. The specified `a.raw[i]` escape for nominal arrays is not yet supported by the execution backend. `unchecked:` is available for a loop you have already proved safe; see the [C++ guide](/docs/guides/cpp-guide#performance-controls-and-escape-hatches). --- # I/O, formatting & contest modes URL: /docs/guides/io-and-formatting Contest programs spend a surprising share of their code reading structured input, formatting answers cleanly, and adapting to single-test, multi-test, interactive, or IOI-grader judges. CP Lang turns all of those into declarative one-liners backed by fast buffered C++17 I/O. ## Typed `read()` The target type drives `read()`. Always put the type on the binding (`let k: Int = read()`) — never pass a type name like `read(Int)` (only a range literal `read(1..=2e5)` or `read(none: -1)` is accepted as an argument). `read()` can fill a fixed-size array (`let a: [0..n]Int = read()`, `let a: [V]Int = read()`), **never** a dynamic `List` (whose length is unknown at compile time). Reading scalars, tuples, records, fixed-size arrays, grids, and strings uses one uniform call: ```cp let n = read(1..=2e5) // ranged read shorthand (checked in run & C++) let m: 0..=2e5 = read() let (l, r): (Int, Int) = read() domain V = 1..=n domain Row = 1..=n domain Col = 1..=n let a: [V]Int = read() let edges: [0..m](u: V, v: V, w: Int) = read() let grid: [Row, Col]Char = read() ``` ### Dependent bounds and domain values Range bounds can reference earlier `let` bindings (`let k: 1..=n = read()`), and reading a domain value `let u: V = read()` automatically parses the input integer and checks that it belongs to `V`. In local runs (`cpl run`, `cpl stress`), out-of-range inputs trap immediately; in `cpl build` release C++17, fast buffered parsing eliminates `cin`/`sync_with_stdio` boilerplate. ### Sentinels and EOF loops When a problem uses a sentinel integer like `-1` or `0` to mean "no parent" or "missing", decode it into `?T` directly at the boundary with `read(none: sentinel)`: ```cp let n = read(1..=2e5) domain V = 1..=n let parent: [V]?V = [V] _ => read(none: -1) print(parent, none: "-1") ``` For problems that terminate on a sentinel value, write an ordinary `loop:`: ```cp loop: let (n, m): (Int, Int) = read() if (n, m) == (0, 0): break // stops when (0, 0) is read print(n + m) ``` Use `@!multitest(until_eof)` for repeated test cases ending at EOF. `read()` currently reads whitespace-delimited tokens; a full-line `read_line()` API is not implemented. ### Character-encoded grids and state enums Read a character grid and map its alphabet to enum states with `match`. Automatic `@tags` I/O is specification-only in the current execution backend: ```cp let n: 1..=50 = read() let m: 1..=50 = read() domain Row = 1..=n domain Col = 1..=m enum Cell: Empty Wall Start End let grid: [Row, Col]Char = read() for r in Row: for c in Col: let ch = grid[r, c] assert ch in ".#SE" let cell = match ch: '.' => Empty '#' => Wall 'S' => Start _ => End if cell == Start: print(r, c) ``` ## Output with `print()` and format strings `print(...)` separates arguments with single spaces and writes a trailing newline. Arrays and lists print space-separated on one line, and `yes(b)` turns a `Bool` into `YES` or `NO` (the standard contest convention): ```cp let ans = 42 let (a, b) = (3, 7) let arr = [3, 7] let dist: List = [0, none, 7] let ok = true print(ans) // single value print(a, b) // space-separated: "3 7" print(arr) // space-separated elements on one line (note: [D]Char prints contiguously; pass sep: " " for spaced chars) print(arr, sep: "\n") // one element per line print(dist, none: "-1") // prints ?Int array, writing -1 for every none print(yes(ok)) // YES or NO (for AtCoder Yes/No, use `print(if ok: "Yes" else: "No")`) ``` ### String interpolation and format specifiers Interpolate any expression inside `"..."` with `{expr}` and optional format specifiers after `:`: ```cp let (tc, ans, n) = (1, 42, 42) let x = 7.0 / 3.0 let (num, den) = (1, 7) print("Case #{tc}: {ans}") // string interpolation print("{n:5}") // width 5, space-padded print("{n:05}") // width 5, zero-padded ("00042") print("{x:.6f}") // fixed-point float, 6 decimal places (never -0.00) print("{x:8.2f}") // width 8, 2 decimal places print("{n:x}") // lowercase hex print("{n:b}") // binary print(fixed(num, den, 6)) // exact integer rational formatted to 6 decimal places ``` Notice `fixed(num, den, k)`: when a problem asks for `p / q` to `k` decimal places and you want exact rounding without `F64` precision loss, `fixed(num, den, k)` formats the exact decimal digits directly from integers. ## Single-test vs `@!multitest` Single-test and multi-test solutions have the exact same top-level structure — there is no `fn solve()` wrapper: ```cp // Runs ONCE before the test loop (great for sieves, factorials, lookup tables): let cb = Comb>(200_000) @!multitest // reads t and loops everything below t times let (n, k): (1..=2e5, 0..=2e5) = read() if k > n: print(0) return // ends ONLY the current test case print(cb.choose(n, k)) ``` Three rules make `@!multitest` effortless: - `@!` is a file-level directive applying from that line downward, whereas `@` always attaches to the single declaration below it. - Everything below `@!multitest` runs in a fresh scope for each test case, and every `@memo` function declared below it automatically resets its cache between cases. - Bare top-level `return` exits the program in a single-test file or ends the current test case below `@!multitest`. - Use `@!multitest(until_eof)` for judges that repeat test cases until end-of-file without a leading count `t`. ## Interactive problems (`@!interactive` and `ask`) In interactive problems, forgetting `flush` causes Idleness Limit Exceeded. Put `@!interactive` at the top of the file to flush every `print(...)` automatically, or use `ask(...)` — it prints the query, flushes stdout automatically, and parses the judge's reply into the expected type: ```cp fn at_least(x: Int) -> Bool: let reply: Str = ask("?", x, limit: 30) reply == ">=" let ans = (1..=1_000_000_000).first_true(at_least)! print("!", ans) ``` Passing an optional `limit:` lets the co-located `@interactor` enforce your query budget locally and print the exact failing transcript if you exceed it. ## IOI / function-only graders (`@grader`) For IOI-style problems where the judge supplies `main()` and calls your functions (while exposing grader callbacks), mark extern and entry functions with `@grader`: ```cp @grader fn query(l: Int, r: Int) -> Int @grader fn solve(n: Int) -> Int: query(0, n - 1) ``` When compiling with `cpl build`, CP Lang emits the exact C++ function signatures expected by the judge header instead of generating a `main()` function. --- # Standard & local libraries URL: /docs/guides/stdlib The standard library is written in ordinary CP Lang rather than hardwired into the compiler. Every container shares one uniform vocabulary — `.len`, `.is_empty`, `.clear()`, `.take()` (an `O(1)` move-out leaving the container empty) — and compiles down to flat, tree-shaken C++17. The prelude auto-imports common types and helpers (capped at 80 names), including `bfs`, `topo`, `peel`, and `resized`; the examples below need no imports for those names. ## Standard library modules Every module under `spec/std/` is plain CP Lang. Import individual names with `use std..{Name}`: | Module | Key exports | Purpose | | --- | --- | --- | | `std.algebra` | `Monoid`, `Action`, `Desc`, `desc`, `Reversible`, `MaxSub`, `fold` | Algebraic traits, Kadane monoid, descending key wrapper | | `std.bag` | `SortedBag`, `SortedSet`, `BagCursor` | Ordered multiset & unique-key set with `.range(r)` views, rank, nth, cursors, and node recycling | | `std.beats` | `BeatsSegTree` | Ji Driver Segment Tree Beats (`chmin`, `chmax`, `add`, `sum`, `min_val`, `max_val`) | | `std.bitset` | `Bitset` | Fixed-domain bitset with bitwise ops and `.first_set` | | `std.derive` | `eq_fields`, `lt_fields`, `show_fields`, `read_fields`, `Hash`, `hash_fields`, `Gen`, `gen`, `gen_fields` | The field-by-field `Eq`, `Ord`, `Show`, `Read`, `Hash` and `Gen` (a seeded random value for stress tests: `let p: P = gen_fields(mut rng)`), written on `fields`; call one from an `impl` (`fn lt(a, b) = lt_fields(b, a)` orders the other way, `fn hash(self) = hash_fields(self)` hashes a struct) | | `std.deque` | `Deque` | Double-ended queue (`.push_front`, `.pop_front`, `Deque.of`) | | `std.dp` | `LiChao`, `Line`, `dnc_dp`, `knuth_dp`, `aliens_search`, `monotone_minima` | DP optimizations (Li Chao tree, D&C DP, Knuth DP, Aliens/WQS, SMAWK) | | `std.slope` | `Concave`, `Convex` | Slope trick: integer concave/convex functions as sorted slopes | | `std.dsu` | `Dsu`, `DsuOf`, `ParityDsu`, `PotentialDsu`, `RollbackArray` | Disjoint set union (payload, parity, potential) and rollback array sharing `Mark` | | `std.fenwick` | `Fenwick`, `XorFenwick`, `Fenwick2D`, `DualFenwick`, `RangeFenwick` | 1D/2D Fenwick, XOR, range-add/point-get, and range-add/range-sum | | `std.flow` | `Arc`, `FlowGraph`, `CostFlow`, `max_matching`, `max_weight_matching`, `max_closure`, `gomory_hu`, `global_min_cut` | Dinic, min-cost flow, matchings, closure, bounded flows, cut trees | | `std.geometry` | `Pt`, `Vec`, `turn`, `ByAngle`, `convex_hull`, `minkowski_sum`, `closest_pair`, `hull_tangents`, `half_plane_intersect`, `min_enclosing_circle`, `circle_polygon_area` | Exact 2D integer geometry (`I128` predicates, hulls, calipers, closest pair) and careful floating-point geometry | | `std.graph` | `Graph`, `Tree`, `bfs`, `dijkstra`, `peel`, `topo`, `scc`, `two_color` | CSR graphs, implicit-neighbor algorithms, `Tree` alias | | `std.grid` | `adj4`, `adj8`, `step`, `ray`, `Dir4`, `Dir8`, `transposed` | No grid type: a cell is a `(Row, Col)` pair over two domains, so `p.adj4` and `p.adj8` are its in-bounds neighbours, `p.step(d)` and `p.ray(d)` walk a `Dir4`/`Dir8`, and `bfs(p => [q for q in p.adj4 if open[q]], [start])` searches the grid | | `std.hashmap` | `FlatMap` | Open-addressing splitmix64-salted flat hash map for `Int` keys | | `std.heap` | `MinHeap`, `MaxHeap`, `ErasableMinHeap`, `ErasableMaxHeap`, `IndexedMinHeap`, `IndexedMaxHeap` | Binary, lazy-delete, and domain-keyed priority queues | | `std.interval` | `IntervalMap` | Maximal-run interval partition over a domain with O(log n) amortized range assign | | `std.lazy` | `LazyTreap`, `Rope`, `Flip`, `flip_action` | Lazy treap, rope, and the flip action. Lazy range updates on a segment tree are `SegTree(..., act:)` in `std.segtree` | | `std.marks` | `Marks`, `MarkMap`, `Interner` | Generation-stamped O(1)-reset visited set/map and online key interner | | `std.math` | `gcd`, `lcm`, `ext_gcd`, `ceil_div`, `choose2`, `Sieve`, `sieve_multiplicative`, `factor`, `divisors`, `inv_mod`, `crt`, `crt_all`, `mod_log`, `mod_sqrt`, `floor_sum`, `bit_len` | Number theory, primes, CRT, discrete log/sqrt, bit helpers | | `std.matrix` | `Mat`, `det_real`, `rank_real`, `solve_real`, `inverse_real`, `XorBasis` | Dense matrices, exact and floating-point Gaussian elimination, GF(2) XOR bases | | `std.mo` | `mo`, `mo_order`, `mo_steps` | Mo's offline range-query driver, ordering, and window transitions | | `std.mod` | `Mod

`, `Comb` | Compile-time and runtime modular arithmetic and combinatorics | | `std.ntt` | `ntt`, `convolve`, `convolve_mod`, `convolve_int`, `SosOver`, `sos`, `fwht`, `convolve_or`, `convolve_and`, `convolve_xor`, `convolve_subset` | NTT, linear/cyclic/3-prime/exact convolution, SOS, FWHT, bitwise/subset convolutions | | `std.poly` | `deriv`, `integral`, `inv`, `log`, `exp`, `pow`, `sqrt`, `eval`, `div_mod`, `prod_linear`, `taylor_shift`, `eval_all`, `compose`, `lagrange_at`, `interpolate` | Formal power series, multipoint ops & interpolation over NTT (`List>`) | | `std.persistent` | `PersistentSegTree`, `Version`, `RangeKth` | Path-copying persistent segment tree and O(log n) range k-th smallest | | `std.prefix` | `prefix`, `Prefix`, `FillOrder`, `prefix_fold`, `suffix_fold`, `Diff` | 1D/2D/list static (`prefix(a)`) and append-only (`Prefix<...>.filling(order:)`, `.set(...)`) prefix/suffix sums, monoid folds, 1D/2D difference arrays | | `std.rand` | `Rng` | Seeded deterministic RNG (`.int(lo, hi)`, `.next()`) | | `std.segtree` | `SegTree`, `MergeSortTree`, `SparseSegTree` | Segment tree, orthogonal 2D merge-sort tree, and coordinate-sparse segment tree | | `std.seq` | `Perm`, `pairs`, `with_prev`, `cyclic_pairs`, `windows`, `scan`, `scan_in_place`, `argmax`, `inversions`, `prev_less`, `next_less`, `sliding_min`, `inverse`, `perm_cycles`, `first_true`, `last_true` | Sequence views, searches, monotone stacks, permutations, folds, `Perm` alias | | `std.sparse` | `SparseTable`, `DisjointSparseTable`, `idempotent` | O(1) idempotent and non-idempotent associative range folds | | `std.spec` | `convexity_break`, `monge_break`, `dnc_break`, `knuth_break`, `berlekamp_massey`, `differences`, `newton` | Conjecture checking and sequence/recurrence discovery | | `std.strings` | `z_function`, `prefix_function`, `manacher`, `SuffixArray`, `SuffixAutomaton`, `PalindromicTree`, `Trie`, `AhoCorasick`, `RollingHash`, `Hash2D` | Pattern matching, palindromes, suffix structures, tries, and rolling hashes | | `std.timetree` | `TimeTree`, `TimeStep` | Offline segment tree over time for rollback-based dynamic structures | | `std.tour` | Tour re-exports | Euler tour utilities | | `std.tree` | `Rooted`, `Centroids`, `LinkCut`, `LazyLinkCut`, `JumpTree`, `PermTree` | Rooted tree, Euler tour, LCA, HLD path queries, rerooting DP, virtual trees, centroid decomposition, link-cut trees, trees grown leaf by leaf, permutation trees | | `std.window` | `MonoDeque`, `WindowFold` | Sliding-window extrema and inverse-free monoid window folds | ## Prelude collections Construct empty `List` and `Deque` with `= []`; construct all other containers with `Type()`. - **`List`:** `.push(x)`, `.push_id(x) -> Int`, `.pop() -> ?T`, `.insert(i, x)`, `.remove(i) -> T`, `.swap(i, j)`, `.first -> ?T`, `.last -> ?T`, `xs[l..r]`, `xs + ys`, and `xs.freeze() -> (domain D, [D]T)` for arena construction. - **`Deque`:** `.push(x)`, `.pop() -> ?T`, `.push_front(x)`, `.pop_front() -> ?T`, `.first -> ?T`, `.last -> ?T`, `q[i]`. - **`MinHeap()` / `MaxHeap()`:** `.push(x)`, `.pop() -> ?T`, `.peek -> ?T`. For mixed-order keys inside tuples or `sort(..., by:)`, wrap descending fields with `desc(x)` (type `Desc`): ```cp use std.algebra.{desc} domain V = 0..4 let (dist, u) = (3, V(0)) type Item = (cost: Int, value: Int) var items: List = [(2, 10), (1, 5)] var pq = MinHeap<(Int, Desc)>() pq.push((dist, desc(u))) items.sort(by: x => (x.cost, desc(x.value))) ``` - **`Set()` / `SortedSet()` / `SortedBag()`:** `.add(x)`, `.remove(x)`, `x in s`, `.first`, `.last`. `Set` supports `.first_ge(k)`/`.first_gt(k)`/`.last_le(k)`/`.last_lt(k)`. `SortedSet` (unique keys) and `SortedBag` (keeps duplicates, with `.count(x)` and `.remove_one(x)`) support `.range(r)` — an O(1) view over any range (including open-ended `..b`, `..=b`, `a..`, `..`) whose `.first`, `.last`, `.len`, `.is_empty` cost O(log n) and whose iteration (`for x in s.range(r)` / `.rev`) costs O(log n + k). Neighbor lookups return `?K`, so an absent key is `none` rather than a sentinel. - **`Map()` / `HashMap()`:** `m[k]` traps if `k` is absent (store `m[k] = v` first, or use `m.get(k) -> ?V` which never traps or inserts), `m[k] f= x` (auto-inserts from the operator identity: `0` for `+=`/`-=`, `none` for `min=`/`max=`), `(m[k] ??= init).push(x)` (always parenthesize `??=` when chaining or using as an expression — never `let v = m[k] ??= init`), `m.remove(k) -> ?V`, `k in m`, `for (k, v) in m.items`. Ordered `Map` lookups (`.first_ge(k)`, `.last_le(k)`) return `?(K, V)`. All hash tables use per-process splitmix64 salting to defeat anti-hash tests. `m.get_or_insert(k, v)` stores `v` when `k` is absent and returns the stored value. - **`Bitset()` & `Subset`:** `Bitset` provides `Bitset.of(xs)` (from a `List` or generator `k for k in D if ...`), `Bitset.from(a)` (from `[D]Bool`), `.add(v)`, `.remove(v)`, `.toggle(v)`, `v in s`, `|`, `&`, `-`, `^`, `.len` (popcount), `.first_set -> ?D`, `s.shifted(k)`. `Subset` (`D.K <= 25`) is a 4-byte `Index` value for bitmask DP: `Subset.empty`, `Subset.full`, `Subset.single(v)`, `s.first -> ?D`, `s.with(v)`, `s.without(v)`, `s.complement`, `for mask in Subset`, `for v in mask`, and `for sub in mask.subsets`. `s = s.set(v, on)` returns a copy with `v` put in or taken out by a `Bool`; on its own, `s.set(v, on)` leaves `s` unchanged. ## Search, sorting, and sequence helpers `Deque.of(xs)` starts a queue from a list in front-to-back order. `a.resized(n, fill)` returns a new list, truncated or padded to length `n` in O(n); it does not mutate `a`. The same prelude helper can be called as `resized(a, n, fill)`: ```cp let xs = [1, 2] var q = Deque.of(xs) print(q.pop_front()!, q.pop_front()!) // 1 2 print(xs.resized(4, 0)) // 1 2 0 0 print(resized(xs, 1, 0), xs) // 1, then the unchanged 1 2 ``` Answer-space binary search uses two free functions (`F64` ranges take `steps: 80`), both returning `?I`: ```cp let n = 10 let budget = 25 fn feasible(x: Int) -> Bool: x >= 42 fn cost(k: Int) -> Int: k * k let ans = (1..=1e9).first_true(x => feasible(x)) let hi = (0..=n).last_true(k => cost(k) <= budget) print(ans, hi) ``` Sorted lookup uses `.first_ge(x)`, `.first_gt(x)`, `.last_le(x)`, `.last_lt(x)` everywhere, with the return type matching the container: - On an array, `List`, or slice: returns the **index** (`?D` or `?Int`). - On a `Set` or `SortedBag`: returns the **key** (`?K`). - On a `Map`: returns the **pair** (`?(K, V)`). Other prelude sequence helpers: - `compress(all)` — coordinate compression producing a nominal domain `xs.D`, inverse `xs[id]`, `xs.at(val) -> xs.D`, and `xs.first_ge(val) -> ?xs.D`. - `Prefix(a)` — 1D (`List`, `[D]T`) or 2D (`[R, C]T`) prefix sums (`pre.fold(l..=r)`, `pre.prefix(cut)`); for DPs that query already-filled cells while filling, use `Prefix.filling(order: FillOrder.Forward | FillOrder.Reverse)` / `Prefix.filling(order:)` / `Prefix.filling(n, order:)` with O(1) `.set(...)` in fill order. - `scan(a, +)` / `scan(a, max)` — inclusive running folds (`a.scan_in_place(+)` in `std.seq` mutates a `List` without allocation); `a.fold(+)` / `a.fold(gcd)` / `a.fold((x, y) => ...)` — whole-sequence left fold across every `Seq` (monoids return their identity when empty; binary functions `(T, T) -> T` follow the same empty-sequence rule as `min`/`max`: trap when empty, or return `?T` with `!` / `??`); `a.excl_fold(+)` — yields `(x, rest)`, the fold of every other element, without division. - `a.runs()` / `a.runs(by: key)` — run-length `(val, len)` pairs; `a.chunk_by(same)` (in `std.seq`) splits adjacent runs into slices and `a.group(by: key)` groups all elements by key; `xs.adjacent` — consecutive pairs; `D.windows(k)` — sliding windows. - Sequence methods (prefer method form over free calls on one sequence): `a.sort(by:)`, `a.sorted(by:)` (O(n log n), returns a 0-indexed `List`; descending via `desc: true` or `by: desc`; custom strict-weak-order comparator via `cmp: (a, b) => Bool`, mutually exclusive with `by:`), `D.sort(by: key)` (for domains), `a.reverse()`, `a.deduped()` (adjacent duplicates only, O(n) without hashing; in-place `dedup(mut a)` in `std.seq`), `a.distinct()` (all duplicates in first-seen order across any `Seq`, O(n) expected time / O(n) space via hashing); in `std.seq`: `rotate_left(mut a, k)`, `rotate_right(mut a, k)`, `next_permutation(mut a)`, `prev_permutation(mut a)`, `p.inverse()`, `perm_cycles(p)`. - Method-form folds & searches: `xs.sum()`, `xs.prod()`, `xs.min(by:)`, `xs.max(by:)`, `xs.argmax(by:)`, `xs.argmin(by:)`, `xs.count(p)`, `xs.all(p)`, `xs.any(p)`, `xs.first(p) -> ?T`, `xs.find(x) -> ?I`, `xs.group(by: k)`. Use free `sum(f(x) for x in xs)` for generator expressions and `min(a, b)` / `max(a, b)` for two or more values. - `xs.windows(k)` yields every length-`k` window as a list; `zip(xs, ys)` pairs elements up to the shorter list. - `std.seq` also provides zero-allocation sequence views `pairs(xs)` (consecutive `(a, b)` pairs), `with_prev(xs)` (`(?T, T)` with `none` on the first element), `cyclic_pairs(xs)`, and the standard permutation alias `Perm = [V]V` (paired with `std.graph.Tree` for `cpl stress` generation and shrinking): ```cp use std.seq.{Perm, pairs, with_prev} use std.graph.{Tree} let xs = [1, 4, 9] var diffs = 0 for (a, b) in pairs(xs): diffs += b - a var jumps = 0 for (prev, cur) in with_prev(xs): if let p = prev: jumps += cur - p print(diffs, jumps) ``` - Randomness: `rand(lo, hi)` and `shuffle(mut xs)` are in the prelude; `std.rand` adds a seeded `Rng.new(seed)` with `.int(lo, hi)` and `.next()`. ## Range data structures and union-find Range structures accept bare associative operators (`+`, `*`, `^`, `&`, `|`, `min`, `max`, `gcd`) directly, or a custom `Monoid(id: identity, op: combine)`. A segment tree with range updates takes `act:`, either a stock action (`add`, `assign`, `affine`, `flip`) or a custom `Action(id:, compose:, apply:, over:)`. Name the fields to make each callback's role clear: ```cp status=spec use std.algebra.{Monoid, Action} domain V = 1..=4 let a: [V]Int = 3 struct Node: value: Int fn merge(a: Node, b: Node) -> Node: Node(a.value + b.value) let nodes: [V]Node = [V] v => Node(a[v]) var bit = Fenwick(a) // sum-only: .add(i, d), .fold(l..=r) var rmq = SparseTable(min, a) // O(1) .fold(l..=r) -> Int (non-empty range) var st = SegTree(+, a) // bare operator var mx = SegTree(Monoid(id: Node(0), op: merge), nodes) var lz = SegTree(+, a, act: add) // range add + range sum let aff = Action( id: (1, 0), compose: (new_f, old_f) => (new_f.0 * old_f.0, new_f.0 * old_f.1 + new_f.1), apply: (f, val, span) => f.0 * val + f.1 * span, over: Monoid(id: 0, op: (x, y) => x + y), ) var affine = SegTree(+, a, act: aff) affine.apply(V(1)..=V(4), (2, 1)) print(bit.fold(V(1)..=V(4)), rmq.fold(V(1)..=V(4)), st.all, mx.all.value, lz.all, affine.all) ``` - `SegTree` provides `.set(pos, val)`, `.at(pos)` (the leaf as a writable place: `st.at(i) += x`, `st.at(i) max= x`, each write `O(log n)`), `.fold(l..=r)`, `.all` (`O(1)` root fold), and `O(log n)` binary search on the tree via `.right_while(from, ok)` and `.left_while(to, ok)`. Empty and inverted ranges are valid no-ops (except `SparseTable.fold`, which asserts a non-empty range and returns `T`). - `Fenwick2D` handles 2D prefix sums; `Fenwick` stays dedicated to sums (`+`/`-`). `bit.kth(k) -> ?V` finds the first index whose prefix sum reaches `k` (non-negative counts). - `Dsu()` provides `.unite(a, b) -> Bool`, `.find(v) -> V`, `.same(a, b)`, `.size(v)`, `.components`, `.groups() -> List>`, plus `.mark() -> Mark` and `.undo_to(snap)` for `O(1)` rollback DSU. `DsuOf(init, join)` keeps a value per set (joined on merge, restored on `undo_to`), and `ParityDsu` tracks same/opposite sides with `.unite(a, b, differ:)`, `.diff(a, b) -> ?Bool` and `.consistent`. - `std.marks.Marks` is an opt-in 32-bit generation-stamp visited table (`O(1)` reset); for most problems, `[D]Bool` with a touched-list reset is simpler and equally fast. ## Graphs, trees, flows, and strings - **`Graph` / `Graph` (`std.graph`):** flat CSR storage via `Graph.undirected(es)`, `Graph.directed(es)`, and neighbor iteration `g[u]`. Algorithms accept either a `Graph` or an implicit neighbor function `v => ...`: `topo`, `peel`, `find_cycle`, `components`, `scc`, `condense`, `bridges`, `two_edge_components`, `biconnected_components`, `articulation_points`, `two_color`, and `euler_walk(edges, directed:) -> ?Walk`. Searches return `Paths` (`p[v]`, `p.reached(v)`, `p.path(t)`, `p.arcs(t)`, `p.order`): `bfs`, `bfs01(next, from:, w:)`, `dijkstra`, `bellman_ford` (`none` on a reachable negative cycle), `floyd_warshall(w: [V, V]?Int)`, and `fixed_cost_paths(from:, moves:, cost:, step:)` for heap-free search over a few fixed-cost move classes; `until: t` stops any of them once `t` is settled. `TwoSat()` solves 2-SAT over a variable domain `X` with `Lit(x, value)` literals, `add_or`, `implies`, `must`, and `at_most_one`. A lambda's vertex domain is the domain it indexes (`peel(v => adj[v])`), and grid cells `(R, C)` are vertices too: `bfs(p => [q for q in p.adj4 if not wall[q]], [(R(0), C(0))])`. - **`Rooted(g, root)` / `Rooted.weighted(g, root, len)` / `Rooted.forest(g, roots)` / `Rooted.from_parents(par)` (`std.tree`):** a value-owned heavy-first preorder domain `t.Pre` in which every subtree and every heavy chain is one range. Shape: `.parent(v)`, `.children(v)`, `t.heavy[v]`, `.light(v)`, `.depth(v)`, `t.far[v]` (weighted depth), `.size(v)`, `.root_of(v)`. Orders: `t.pos(v) -> t.Pre`, `t.at[p] -> V`, `.sub(v) -> Range`, `.below(v)` (without `v`), `.subtree(v)`, `.reorder(a)`, `for v in t.at` (parents first; `t.at.rev` children first), `t.tour` (`(v, entering)`). Paths: `.lca(a, b)`, `.dist(a, b)`, `.is_anc(a, b)`, `.ancestor(v, k)`, `.step(a, b, k)`, `.lift_while(v, pred) -> ?V`, `.path(a, b)`, `.diameter()`, `.chains(a, b, edges?: Bool)`, `.fold_path(a, b, ds)`, `.apply_path(a, b, mut ds, tag)`, `.virtual(keys)` (a `VirtualTree` over its own domain `vt.K`: `at`, `up`, `len`, `key`). DP: `.down(init, f)`, `.up(m, lift, finish)`, `.reroot(m, lift, finish)` (every root at once, O(n), no inverse needed), `.excl_fold(v, m, f)`, `.shapes()` (isomorphism classes). - **`Centroids(g)` (`std.tree`):** centroid decomposition in O(n log n): `.parent(c)`, `.depth(c)`, `.ancestors(v)` yields `(c, dist)` nearest first, `.piece(c)` yields `(v, dist, branch)`. - **`LinkCut.new(op, a)` (`std.tree`):** a forest under `link(u, v)` and `cut(u, v)`, with `connected`, `root_of`, `fold_path(u, v)` in path order, `set(v, x)` and `lca(u, v, root)`, each amortized O(log n). `LazyLinkCut.new(act, a)` adds `apply_path(u, v, f)` under a `LazySegTree` `Action`. - **`PermTree.of(p)` (`std.tree`):** the binary permutation tree of a bijection `p: [I]V` in O(n): nodes `t.Node` (2n - 1), `t.kind[v]` (`Leaf`, `Incr`, `Decr`, `Partial`, `Full`), `t.left(v)`, `t.right(v)`, `t.span(v)` (positions) and `t.vals(v)` (values), each O(1). - **`JumpTree()` (`std.tree`):** a forest grown by `add(v, p)` in O(1), with `depth`, `ancestor`, `lca` and `lift_while` in O(log n), as on `Rooted`. - **Network flow (`std.flow`):** `FlowGraph()` (Dinic), `CostFlow()` (min-cost flow), `max_matching` (Hopcroft–Karp) with `min_vertex_cover`, `max_weight_matching` / `min_weight_matching` (Hungarian), `general_matching` / `max_weight_general_matching` (Edmonds), `max_closure`, `circulation` / `max_bounded_flow` / `min_bounded_flow`, `gomory_hu` and `global_min_cut`, all over the caller's own domains; a network whose nodes come from several domains numbers them in one domain until sum domains land. - **String algorithms (`std.strings`):** `z_function(s)`, `prefix_function(s)`, `SuffixArray(s)` (`.sa`, `.lcp`), and `RollingHash(seq)` (works on `Str` or any `[D]T`, `.get(l..r) -> HashVal`). ## Modular arithmetic, math, and geometry One `Mod

` type handles both compile-time `const` moduli and runtime-frozen `let` moduli: ```cp const MOD = 998_244_353 type Z = Mod let p: 1..=1e9 = read() type DynamicZ = Mod

``` - **`Mod

` (`std.mod`):** 4-byte storage when `P <= 2^31 - 1`, `+`, `-`, `*`, `/`, `**` (power), `.inv` (getter, no parens), `.try_inv() -> ?Z` (for composite moduli), `.v -> Int` (underlying residue in `0..P`, not `.val` or `.raw`). `print(z)` prints `Mod

` directly. Intentionally omits `Ord`. - **`Comb()` (`std.mod`):** `.fact(n)`, `.inv_fact(n)`, `.choose(n, k)`, `.arrange(n, k)`, `.multinomial(ks)`, `.catalan(n)` (keyed on a `Mod` type `type Z = Mod

`; an immutable `let comb = Comb()` extends its tables lazily). - **Number theory (`std.math`):** `gcd`, `lcm`, `ext_gcd`, `ceil_div`, `choose2`, `pow_mod`, `inv_mod`, `crt`, `crt_all`, `mod_log`, `mod_sqrt`, `primitive_root`, `floor_sum`, `Sieve(n)` (`sv.is_prime(x)`, `sv.factor(x)`, `sv.phi_table()`, `sv.mobius_table()`, `sv.div_count_table()`, `sv.div_sum_table()`, `sv.spf` array of smallest prime factors, `sv.primes: List` — note `Int` has no `.to_idx`; use `sv.primes` or build a prime-index table), `sieve_multiplicative`, `factor(n)`, `divisors(n)`, `divisors_from_factors(fs)`. (`isqrt` and `bit_ceil` are in the prelude — call `isqrt(n)` directly without `use std.math.isqrt`.) - **NTT & convolutions (`std.ntt`):** `ntt

(mut a, inverse:, bit_reversed:)`, `convolve

(a, b, cyclic:)`, `convolve_mod(a, b, m, cyclic:)`, `convolve_int(a, b, cyclic:)`, in-place `sos(mut f, over: Sub | Sup = Sub, inverse:)` and `fwht(mut a, inverse:)`, and `convolve_or`/`convolve_and`/`convolve_xor`/`convolve_subset`. - **Formal power series (`std.poly`):** `deriv`, `integral`, `inv(a, n)`, `log(a, n)`, `exp(a, n)`, `pow(a, k, n)`, `sqrt(a, n) -> ?List>`, `eval(a, x)`, `div_mod(a, b)`, `prod_linear(roots)`, `taylor_shift(a, c)`, `eval_all(a, xs)`, `compose(f, g, n)`, `lagrange_at(ys, x)`, and `interpolate(xs, ys)` over NTT. - **Matrices & XOR basis (`std.matrix`):** `Mat` (`+`, `-`, `*`, `.pow(e)`, `.mul_vec(v)`, `.transpose()`, `.product(n)`, exact-field `.det()`, `.rank()`, `.solve(b)`, `.solve_space(b)`, `.inverse()`), floating-point `det_real`/`rank_real`/`solve_real`/`inverse_real` with explicit `eps:`, and `XorBasis` (`.add`, `.reduce`, `.contains`, `.max_xor`, `.min_xor`, `.kth`, `.merge`, `.monoid`). - **Exact geometry (`std.geometry`):** `Pt` with `.dot`, `.cross`, `.norm2`, `orient(a, b, c)` (`-1 | 0 | 1`), `turn`, `turn_eps`, and `ByAngle` for exact integer angular sorting. ## Local libraries & advanced contest structures Core `std` is intentionally small enough to memorize. Specialized algorithms live in **local libraries** — regular folders of `.cp` files with a `lib.toml` manifest that compile and tree-shake identically to `std`. The repository includes a full sample library (`examples/local-lib/`) covering advanced contest topics: - **Data structures (`ds/`):** `MonoDeque`, `Steps`, `Rope` (implicit treap), `RangeKth` (persistent segtree), `LiChao` & `LiChaoArena`, `Tri` (triangular interval index), `PotentialDsu`, `Cover` (union-of-intervals), `TwoStackFold`, `mo_order`, `XorBasis`, `Interner`, and `RollbackArray`. - **Math & polynomials (`math/`):** `Frac`, `Fixed`, `Congruence` (general CRT), `Hom` / `BothWays`, `Mat

` (Gaussian elimination / `det` / `rank`), `Poly` / NTT / 3-prime MTT / Lagrange interpolation, `Powers`, SOS DP (`sos_sub`/`sos_sup`), Miller-Rabin + Pollard's rho (`primes`), and `floor_sum`. - **Graphs & DP (`graph/`, `dp/`, `geom/`, `str/`, `seq/`):** `TwoSat`, `Functional` graphs, `KruskalTree`, `mst`, `shortest`/`walk_back`, `convex_hull`, `Dir8`, divide-and-conquer DP (`dnc_opt`), Knuth DP (`knuth`), `palindromes` (Manacher), `Trie`, `SuffixAutomaton`, `AhoCorasick`, `Hash2D`, `lis`, and `fold_others`. ### Starting your own local library Create a directory with a `lib.toml` manifest and register it in your workspace's `cp.toml`: ```toml cp.toml [libs] lib = "../my-cp-lib" ``` Then import modules directly from any solution: ```text use lib.ds.li_chao.{LiChao, Line} use lib.graph.two_sat.{TwoSat} ``` Only `pub` declarations are exported, `@test` blocks live beside each module for `cpl test`, and `cpl build` inlines and tree-shakes only the functions your solution actually calls into the single submitted `.cpp` file. --- # Stress testing URL: /docs/guides/stress When a fast solution disagrees with your intuition, `cpl stress file.cp` generates small valid inputs, runs your solution against an oracle or checker, shrinks the first failing case to a minimal counterexample, and prints it in input format. All verification functions (`@alt`, `@gen`, `@check`, `@interactor`) live in the same `.cp` file and are stripped automatically by `cpl build`. For memoization, assertions, `debug(...)`, and the visual Trace debugger, see [Memoization, stress testing & Trace](/docs/guides/testing). ## 1. Brute oracle with `@alt` (typed input generation) When every `read()` has a range or length type, you do not need a generator at all. Add an `@alt(program)` oracle (or `@alt(fn_name)` for a single function) and run `cpl stress solution.cp`: ```cp status=runs input="3\n2 9 4\n" let n: 1..=10 = read() let a: [0..n]1..=100 = read() var best = 0 for x in a: best max= x print(best) @alt(program) fn slow(): var best = 0 for i in 0..n: if a[i] > best: best = a[i] print(best) ``` `cpl stress` derives a generator and constraint-respecting shrinker from `n: 1..=10` and `a: [0..n]1..=100`, runs cases deterministically from `--seed 1`, and shrinks any failing case before saving it to `.tests/stress-.in`. ## 2. Custom generator with `@gen` When inputs have structure beyond independent ranges (sorted sequences, trees, graphs, or problem-specific invariants), write a `@gen fn` that prints one test case using `rand(...)` and `shuffle(...)`: ```cp status=runs input="4\n0 1 1 2\n" fn solve(n: Int, a: List) -> Int: var total = 0 for x in a: total += x total @alt(solve) fn slow_solve(n: Int, a: List) -> Int: var total = 0 for i in 0..n: total += a[i] total @gen fn make_case(size: Int): let n = rand(1, size) print(n) var a: List = [] for i in 0..n: a.push(rand(0, i)) print(a) let n: 1..=12 = read() let a: [0..n]0..=12 = read() print(solve(n, a)) ``` Every `rand` and `shuffle` call inside `@gen` draws from a replayable choice stream, so `cpl stress` shrinks generated inputs automatically without a hand-written shrinker. ## 3. Constructive validator with `@check` For problems with multiple valid answers, write a `@check fn` that reads the solution's output with `read_output()` and asserts validity: ```cp status=runs input="4\n" let n: 1..=20 = read() if n % 2 == 1: print(-1) else: var out: List = [] for i in 0..n: out.push(if i % 2 == 0: 1 else: -1) print(out) @check fn judge(): if n % 2 == 1: let k: Int = read_output() assert k == -1 else: let a: [0..n]Int = read_output() var s = 0 for x in a: assert x == 1 or x == -1 s += x assert s == 0 ``` `@check` runs on every generated input; an assertion failure reports `WA` with the shrunk input and your solution's output. ## 4. Interactive judge with `@interactor` For interactive problems, declare `@!interactive` and write an `@interactor fn` taking `mut sol: Interactor`. Hidden test data is read inside `@interactor` using typed `read()`, so `cpl stress` generates and shrinks hidden inputs too: ```cp status=runs @!interactive let n: 1..=20 = read() var lo = 1 var hi = n while lo < hi: let mid = (lo + hi) / 2 let ans: Int = ask("?", mid) if ans == 1: hi = mid else: lo = mid + 1 print("!", lo) @interactor fn judge(mut sol: Interactor): let n: 1..=20 = read() let secret: 1..=n = read() sol.send(n) var queries = 0 while true: let kind: Str = sol.recv() if kind == "?": queries += 1 assert queries <= 6 let x: Int = sol.recv() sol.send(if secret <= x: 1 else: 0) else: let guess: Int = sol.recv() assert guess == secret return ``` ## Common CLI commands ```bash # Stress with deterministic seed and size cap cpl stress solution.cp --cases 200 --seed 1 --size 8 # Show the first variable assignment where fast and @alt diverge cpl stress solution.cp --explain # Machine-readable report (same JSON schema as browser stress) cpl stress solution.cp --format json # Run saved samples and stress counterexamples (supports .out and .ans) cpl test solution.cp cpl test solution.cp --tests corpus/problems/ccc03s4/tests # Write a paste-ready, privacy-redacted bug report (or `--last` after an ICE) cpl report solution.cp --input sample.in --shrink cpl report --last ``` --- # Strings & ASCII text URL: /docs/guides/strings `Char` is one ASCII byte. `Str` is a flat, value-semantic sequence of those bytes indexed by `0..s.len`. There is no UTF-8 decoding, variable-width character indexing, Unicode normalization, or hidden code-point iterator behind a subscript. > **Deliberate scope.** Non-ASCII text is outside the `Char`/`Str` contract. Character and string literals must be ASCII. Arbitrary binary bytes belong in an explicit byte container rather than a string that silently changes encoding. ## Value-semantic, `0..len`-indexed `Str` In CP Lang, `Str` is a flat `0..s.len`-indexed ASCII byte sequence with O(1) indexing and O(1) lent slices (`s[l..r]` borrows from `s` for the current block; call `s[l..r].to_str()` when returning a slice from a function or appending it with `t += s[..k].to_str()`): ```cp let s: Str = read() if not s.is_empty: let ch = s[0] // Char; digit: ch - '0', letter: ch - 'a' let sub = s[..min(3, s.len)] print(ch, sub) var out = "" out.push('a') for _ in 0..3: out += "bc" // mutable byte buffer when `var` if s.len >= 2 and s[..2] == "ab": print(out) ``` Because `Str` has value semantics, `var t = s` moves or copies cleanly without hidden aliasing; call `s.copy()` when you want an independent mutable copy while keeping `s`. You can run `Str` indexing, slicing, concatenation, and ASCII arithmetic directly in the [playground](/play). ## Common string helpers The current toolchain supports these operations directly: - Indexing and slices: `s[i]`, `s[l..r]`, `s[..k]`, `s[k..]`, `s.len`, `s.is_empty`. Slices are lent views: call `s[l..r].to_str()` to materialize an owned `Str` for returning from a function or appending (`out += s[..k].to_str()`). - Numbers to strings: use string interpolation `let s = "{n}"` (integers have no `.to_str()` method); use `std.math.digits(n)` for base-10 digits. - Building: `var out = ""`, `out.push(c)`, and `out += t`. String repetition with `*` is not yet implemented; append in a loop. - Prefix matching: guard the length, then compare `s[..prefix.len] == prefix`. For input, `read()` parses whitespace-delimited typed tokens. - Character arithmetic & tests: `c - '0'`, `c - 'a'`, `'A' + (c - 'a')`; test ranges with `'a' <= c and c <= 'z'` (`..=` ranges are `Int`-only, not `Char`). - Nominal character domains: `let s: [domain S]Char = read()` introduces `S` (`let`, not `var`); for a mutable character array, read `let raw: Str = read()`, declare `domain S = 0..raw.len`, and copy into `var s: [S]Char = [S] i => raw[i.to_idx]`. ## Opt-in nominal character domains When you are writing a two-string DP (such as LCS or edit distance) and want the compiler to forbid mixing an index into string `a` with an index into string `b`, opt into a nominal character domain `[domain A]Char`: ```cp let a: [domain A]Char = read() let b: [domain B]Char = read() var dp: [A.cuts, B.cuts]Int = 0 for i in A: for j in B: dp[i.r, j.r] = if a[i] == b[j]: dp[i.l, j.l] + 1 else: max(dp[i.l, j.r], dp[i.r, j.l]) print(dp[A.last!.r, B.last!.r]) ``` Swapping an `A` boundary with a `B` boundary is a compile error, and `.l`/`.r` carry the empty-prefix boundary cleanly. When the length is already read into a domain, the same `[S]Char` form runs directly in both `cpl` and the browser WebAssembly playground: ```cp let n: 1..=100 = read() domain S = 1..=n let word: [S]Char = read() print(word.count(c => c == 'a')) ``` For input `5` and `abaca`, the result is `3`. Each subscript touches one contiguous byte in O(1). ## String algorithms in `std` The standard library provides `z_function(s)`, `prefix_function(s)`, `palindromes(s)`, `SuffixArray(s)` (`.sa`, `.lcp`), and double-salted `RollingHash(s)` (`.get(l..r)`), all operating directly on flat ASCII bytes. For a real multi-DP string port using `0..n`-indexed `Str`, see the [corpus](/corpus). ## Prefix, suffix, and search helpers `Str` has `.starts_with(p)`, `.ends_with(p)`, `.find(p) -> ?Int` (first match of a `Char` or `Str`), `.rfind(p) -> ?Int` (last match of a `Char` or `Str`), substring membership `sub in s`, and `s.find_all(p)` (every match start, overlaps included). `Char` has `.lower`, `.upper`, and `.digit` for `'0'..='9'`. All of them are in the prelude. ```cp let s: Str = "banana" print(yes(s.starts_with("ba")), yes(s.ends_with("na")), yes("an" in s)) // YES YES YES print(s.find("an"), s.rfind("an"), s.rfind('a')) // 1 3 5 print('a'.upper, 'Q'.lower) // A q ``` --- # Memoization, stress testing & Trace URL: /docs/guides/testing Contest bugs rarely come from the algorithm idea — they come from an edge case you did not construct by hand. CP Lang puts memoization, input generators, brute-force oracles, constructive checkers, and local interactors right inside the same `.cp` file, then strips all verification code automatically when `cpl build` emits your submission. ## Memoization with `@memo` Annotate a pure recursive function with `@memo` to cache its results over any `Index` or range parameter tuple: ```cp domain V = 0..20 @memo fn dp(u: V, used: Bool) -> Int: if u == V(0): return if used: 1 else: 0 let prev = u.prev! dp(prev, false) + dp(prev, true) print(dp(V(19), true)) ``` Bare `@memo` chooses its storage layout automatically (`@memo(into: table)` exposes a dense table when you want explicit control): - When every parameter is an algebraic `Index` or range and the total state count is at most `2^24`, `@memo` allocates a flat contiguous dense table with zero hashing overhead. - Larger state spaces fall back automatically to a per-process salted open-addressed hash table. - A `@memo fn` declared inside a function, inside a loop, or below `@!multitest` resets its cache automatically on every call, iteration, or test case — eliminating stale-table Wrong Answers. - `@memo` can also wrap `ask(...)` or an extern `@grader fn` so repeated queries with the same arguments cost only one judge query. - If you want manual hash storage instead, declare `var dp = HashMap()`. Try a live cached `@memo` DP in the [playground](/play). Here is a small recursive recurrence you can run directly: ```cp let n: 1..=20 = read() // Small linear recurrence (see memo_dp.cp for cached @memo DP). fn f(i: Int) -> Int: if i == 0: return 1 f(i - 1) * 3 + i print(f(n - 1)) ``` For input `4`, `f(3)` evaluates to `45`. ## Assertions and `debug` There is one assertion keyword, so a sanity check is never silently stripped in release mode: - `assert cond` — checked in both local runs and compiled C++17, and also informs range and disjointness checks. Input constraints belong in typed `read()` bounds, `read(gen: f)`, `@gen`, and `@check` rather than assertions. - `debug(x, dp)` — prints checkpoints during local runs, records structured snapshots in `cpl run --trace` and the playground's **Trace** button, and replays side by side when stress testing catches a failing case. `cpl build` omits `debug(...)` from the final judge C++17, so the compiler rejects any `debug(...)` expression that mutates program state (`E0312`). ## Co-located `@alt`, `@check`, `@interactor`, and `@gen` Write your slow reference, constructive validator, or interactive judge in the same file as your solution: ```cp let n: 1..=1000 = read() let a: [0..n]Int = read() print(a.sum()) @gen fn make_case(size: Int): let n = rand(1, size) print(n) print([rand(-10, 10) for _ in 0..n]) @alt(main) fn slow(): var total = 0 for x in a: total += x print(total) @check fn check(): let ans: Int = read_output() assert ans == a.sum() ``` This complete sum program uses `print()` inside `@gen` to produce test input. For an interactive program, use the separate `@interactor` example in the [stress guide](/docs/guides/stress); do not combine its protocol with the sum program. Any program that calls `ask(...)` flushes every `print(...)` automatically. Every generator draws from a replayable choice stream, enabling automatic structure-aware shrinking of failing tests without writing a custom shrinker. ## Pattern and DP structure discovery (`std.spec`) When you have a slow `@alt` solution and want to check whether a sequence obeys a linear recurrence or whether a DP transition satisfies monotonicity, convexity (Aliens/WQS), or the quadrangle inequality (Knuth / divide-and-conquer DP), `std.spec` and local spec helpers let you test hypotheses empirically on small inputs before writing the fast algorithm: ```cp @memo fn tilings(n: 0..=12) -> Int: if n == 0: return 1 if n % 2 == 1: return 0 if n == 2: return 3 4 * tilings(n - 2) - tilings(n - 4) let small = [tilings(n) for n in 0..12] for n in 4..12: assert small[n] == 4 * small[n - 2] - small[n - 4] print("a[n] = 4 a[n-2] - a[n-4] holds on 0..12") ``` ## Visual debugging with Trace Every run in the [playground](/play) has a **Trace** button that records every top-level variable change, every `print`, and every `debug(...)` call — and runs `@alt(main)` side by side when the file defines one — then opens the interactive trace viewer. You can inspect arrays, 2D DP tables, grids, trees, and graphs step by step, scrub backward and forward through execution, and pinpoint the exact step where your fast solution diverges from `@alt(main)`. ## Profiling with `cpl profile` `cpl profile a.cp input.txt` runs the program and prints every source line with how many times it ran and its share of the time: ```text profile of a.cp (interpreter): 1.2 ms line hits time % 3 1 2.1 us 0% for i in 0..n: 4 1000000 612.0 us 51% s += i ``` Time spent in library code is charged to the line that called it. `--native` profiles the C++ of `cpl build` instead, compiled with `g++ -O2` and a counter at each statement: the hit counts are the interpreter's, and the times are what the judge sees. `--format json` gives the same numbers to scripts. ## Coverage with `cpl cover` `cpl cover a.cp` runs the program on every case in `a.tests/` (or the inputs you name; a directory stands for its `.in` files) and lists the lines no input reached and every `if` that went only one way. A sample set that never takes a branch is a test set that cannot catch a bug there. --- # Language tour URL: /docs/guides/tour You already know how to solve the problem. This chapter is about expressing the solution in CP Lang: indentation instead of braces, `?T` instead of sentinels, structural `[0..n]T` arrays alongside nominal domains, and a file that reads like the flow of your algorithm. ## Values, ranges, and mutation Use `let` by default, `var` for bindings that change, and `const` for compile-time constants. `Int` is the default 64-bit signed integer. A range type states the problem's constraint right where the value enters the program. ```cp let n: 1..=100 = read() domain V = 1..=n let a: [V]0..=1000 = read() var total = 0 for v in V: total += a[v] print(total) ``` Range-typed storage uses the smallest fitting integer width while arithmetic runs in 64-bit `Int`. `?Int` represents every 64-bit `Int` plus `none`, and the compiler can pack optional layouts when proven safe rather than reserving `Int.MIN`. Use `U64`, `I128`, and `F64` when you specifically need unsigned 64-bit, 128-bit, or floating-point arithmetic. When you want a plain integer-indexed array without introducing a nominal domain, write the bounds directly and reset with `.fill`: ```cp let n: 1..=100 = read() let k: 1..=100 = read() let a: [0..n]0..=k = read() var cnt: [0..=k]Int = 0 for i in 0..n: cnt[a[i]] += 1 print(cnt) ``` In CP Lang, `cnt.fill(0)` resets the entire array in place (and `seen.fill(none)` resets a `[D]?T` table between test cases). ## Missing is a value `?T` means “a `T`, or `none`”. `??` supplies a fallback, `if let` binds a present value, and `opt!` unwraps when you know it exists. A missing answer is not `-1`, and an unreachable distance is not `1e18`. ```cp let n: 1..=100 = read() domain V = 1..=n let a: [V]Int = read() var best: ?Int = none for v in V: if a[v] % 2 == 0: best = max(best ?? a[v], a[v]) print(best ?? -1) ``` `?Int` and `?F64` lift arithmetic (`+`, `-`, `*`, `/`, `%`, `**`, unary `-`/`+`) and bitwise (`&`, `|`, `^`, `<<`, `>>`, `~`) operators by absorbing `none`, while `min`, `max`, `min=`, and `max=` skip it, so `dist[v] min= dist[u] + w` is a complete relaxation step with no `INF`. `min(a, b)` returns a definite `T` as soon as one side is a plain `T`. Compound `+=`, `-=`, `?V + k`, and `sum` never lift over `?T`; write `dp[u] = dp[u] + w` when you want absorbing addition. When `none` means failure rather than infinity, test it explicitly instead of relying on `min=` to skip it. Stepping a domain position by an integer (`v + 1`, `v - 1`, `v + k`) also returns `?V`, so stepping off either end can never silently read out of bounds. Neither `?T` nor `Mod

` implements `Ord`; when sorting records with optional fields, place `none` explicitly (`by: x => (x.d == none, x.d ?? 0)`). ## Functions, nested helpers, and explicit `mut` Parameters borrow read-only by default. A function that mutates an argument marks it `mut`, and the caller writes `mut` too. There is no implicit deep copy of an array. ```cp domain V = 1..=3 var a: [V]Int = 0 fn add_to(mut a: [V]Int, v: V, delta: Int): a[v] += delta add_to(mut a, V(1), 3) let snapshot = a.copy() ``` A plain nested `fn` can read and mutate captured outer `var` bindings directly—ideal for a DFS that updates `vis` and `order` without threading extra parameters: ```cp domain V = 1..=4 let g = Graph.undirected([(V(1), V(2)), (V(2), V(3)), (V(2), V(4))]) var vis: [V]Bool = false fn dfs(u: V): vis[u] = true for v in g[u] if not vis[v]: dfs(v) dfs(V(1)) print(vis.count(x => x)) ``` Read [ownership & borrowing](/docs/guides/borrowing) for the lexical rules behind `mut` borrows and `lends` projections. ## Parallel assignment, explicit undo, records, and choices Swap or step coupled state with parallel tuple assignment—the right-hand side is evaluated completely before any binding is written: ```cp let (a, b) = (48, 18) var (r0, r1) = (a, b) while r1 != 0: let q = r0 / r1 (r0, r1) = (r1, r0 - q * r1) ``` There is no `defer`. Undo is one explicit line after the work it covers, which also works across sibling branches and early returns: ```cp domain V = 1..=3 var dsu = Dsu() fn solve(v: V) -> Bool: dsu.unite(V(1), v) let left = V(3) let snap = dsu.mark() solve(left) dsu.undo_to(snap) print(dsu.components) var cur: List = [] fn dfs(step: Int): if step == 3: print(cur) return for x in 0..2: cur.push(x) dfs(step + 1) cur.pop() dfs(0) ``` Name record fields instead of remembering `.first.second`, and match enums exhaustively with bare variant names: ```cp let n: 1..=100 = read() let m: 0..=100 = read() domain V = 1..=n var a: [V]Int = 0 type Edge = (u: V, v: V, w: 1..=1e9) let edges: [0..m]Edge = read() enum Move: Add(v: V, delta: Int) Ask(l: V, r: V) let move = Add(V(1), 5) match move: Add(v, delta) => a[v] += delta Ask(l, r) => print(sum(a[v] for v in l..=r)) ``` ## A few C++ habits to leave behind - Write `and`, `or`, and `not` for logical operators, and `elif`, never `else if`. Multi-line expressions continue inside `(...)`/`[...]`/`{...}` or after a trailing binary operator (`and`, `or`, `+`, `-`, `*`, ...); breaking *before* an operator requires `(...)`. - Mutate elements through an indexed loop (`for i in 0..xs.len: xs[i].f()`); there is no `for mut x in xs`. - `..` excludes the end; `..=` includes it. Open-ended ranges `..i`, `..=i`, and `i..` work in slices and range structures (`st.fold(..i)`). - Stepping a nominal domain position with `v + k` or `v - k` returns `?V`: handle it with `if let`, `??`, or `!`. `v.cyc(k)` wraps cyclically. - Use `x min= y` and `x max= y` (any two-argument function works as `x f= y`). - Integer division `/` and remainder `%` use Euclidean semantics: remainder is always in `0..|b|`, so `-7 / 3` is `-3` and `-7 % 3` is `2`. When operands are proven non-negative, C++ codegen lowers straight to native `/` and `%`. `//` is always a line comment. - Break out of nested loops with labels: `'outer: for r in Row:` and `break 'outer`. ## Program structure A program is its top-level statements, run in order from top to bottom. There is no `fn main()` and no `fn solve()` wrapper, with one test case or with many: ```cp let n: 0..=2e5 = read() if n == 0: print("empty") return domain V = 1..=n let a: [V]Int = read() print(a.sum()) ``` A top-level `return` ends the program. It takes no value and works from inside any loop. When the input holds many test cases, add one line. `@!multitest` is a divider. The `!` marks a directive for the rest of the file, where a plain `@` decorates only the one item below it: everything above it runs once, and everything below it runs once per test case. The number of test cases is read for you at the divider. ```cp let sv = Sieve(1e6) // above the divider: built once, shared by every test case @!multitest let n: 0..=2e5 = read() // below the divider: once per test case if n == 0: print("empty") return // ends this test case; the next one starts domain V = 1..=n let a: [V]Int = read() print(a.sum()) ``` The code below the divider is the single-test program, unchanged and unindented. Three things follow from the divider: - Each test case runs in a fresh scope. Its `let`s, `var`s, domains and functions are created anew and are gone when the case ends, so nothing leaks into the next one. - A `@memo fn` below the divider belongs to its test case: the cache starts empty every time. - Below the divider, `return` ends the current test case only. Above it, `return` still ends the program. State that must outlive a test case (a sieve, precomputed factorials, a lookup table) is declared above the divider. `@alt` and `@check` read the top-level input `let`s by name in both shapes: the program's inputs in a single-test file, or the current test case's inputs below the divider. `@!multitest(until_eof)` reads test cases until the input ends instead of reading a count. For any other shape, write a plain `for _ in 0..tests:` loop; a `@memo fn` nested in it resets on every iteration. Library modules contain only declarations—importing a helper never reads input or mutates hidden global state. --- # Types, numbers & control flow URL: /docs/guides/types-and-control This reference covers every primitive type, numeric rule, operator, optional lifting rule, user-defined type, core trait, control-flow construct, and reserved keyword in CP Lang. ## Bindings and constants Every value is declared with one of three bindings: ```cp let n = 10 // immutable value (cannot be reassigned) var ans = 0, ways = 1 // multi-binding on one line const MOD = 1_000_000_007 // compile-time constant, inlined everywhere ``` Blocks are defined by indentation (no braces). Semicolons `;` separate multiple inline statements on one line (`if ok: a += 1; b -= 1` keeps both statements inside the `if` branch; never write a trailing semicolon at the end of a line). Expressions continue across lines automatically after any binary operator, after `=`, or inside open `()`, `[]`, or `{}`. Comments start with `//` (line comments only). ## Numeric types and literals CP Lang has four numeric types: - `Int` — signed 64-bit integer covering `-(2^63 - 1)..=(2^63 - 1)` (the single value `-2^63` is reserved as the niche sentinel for `?Int`, giving zero-overhead optionals). - `U64` — 64-bit unsigned integer with wrapping arithmetic, intended for bit tricks and polynomial rolling hashes. - `I128` — signed 128-bit integer for intermediate products like `(I128(a) * I128(b)) % m`. - `F64` — 64-bit IEEE 754 floating-point number. Integer literals accept underscores (`1_000_000_007`), scientific notation without a decimal point (`1e9`, `2e5`, `1e18` are all `Int`), hex (`0xFF`), and binary (`0b1010`). A decimal point marks an `F64` literal (`0.0`, `1e-9`). Range types such as `0..=1_000_000_000` or `-100..=100` check bounds on entry (in `read()` or explicit casts) and pack into 1, 2, or 4 bytes in arrays and structs automatically. ### Floating-point (`F64`) rules - Integer literals unify directly with `F64` (`let half: F64 = 1 / 2.0`), while `Int` variables require an explicit conversion `F64(x)`. - `Int(x)` on an `F64` is a compile error — choose the rounding direction explicitly with `floor(x)`, `ceil(x)`, `round(x)`, or `trunc(x)`. - `NaN` and `Inf` trap locally as soon as they are produced, which makes `<` a strict total order on `F64`. - Bare `print(x)` on an `F64` is a compile error — specify precision explicitly with `print("{x:.6f}")` (negative zero `-0.0` is normalized to `0.0`). - Compare floats with `abs(a - b) < eps`; `==` and `!=` on `F64` compare exactly (exact `== 0.0` is fine). - Built-in math intrinsics: `sqrt`, `sin`, `cos`, `tan`, `atan2`, `exp`, `ln`, `hypot`, `abs`, and `PI`. ### Scalars and lossless conversions `Bool` (`true`, `false`), `Char` (a single ASCII byte, e.g. `'a'`, `'\n'`), and `Str` (an ASCII byte string). Lossless conversions are written as type calls: `Int(ch)` (`0..=127`), `Char(i)`, and `Int(b)` (`0` or `1`). ## Operators and compound updates - **Arithmetic:** `+`, `-`, unary `+`/`-`, `*`, `/` (Euclidean floor division), `%` (Euclidean modulo, always in `0..|b|`), `**` (exponentiation). When the range checker proves `a >= 0` and `b > 0`, `/` and `%` emit native C++ `/` and `%` with zero overhead. - **Bitwise:** `&`, `|`, `^` (XOR), `~` (bitwise NOT), `<<`, `>>`, plus `&=`, `|=`, `^=`, `<<=`, `>>=`, and helpers `popcount(x)`, `ctz(x)`, `clz(x)`, `bit_len(x)`. - **Ranges:** `..` (half-open) and `..=` (inclusive) bind looser than arithmetic and tighter than comparisons and `in`, so `i in 0..n - 1` parses as `i in (0..(n - 1))`. - **Logic and comparison:** `and`, `or`, `not`, `in`, `not in`, `==`, `!=`, `<`, `<=`, `>`, `>=`. - **General compound updates:** In addition to `+=`, `-=`, `*=`, `/=`, `%=`, any two-argument function `f` can be written as `x f= y` — most commonly `best min= cand`, `best max= cand`, and `g gcd= x`. ## Tropical Optionals (`?T`) Optional types replace sentinel constants like `1e18` or `-1` across the entire language and standard library. `?Int`, `?F64`, `?V` (domain indices), `?Bool`, `?Char`, and `?Enum` are niche-packed with zero extra bytes. ```cp domain V = 1..=3 let (src, v) = (V(1), V(3)) var dist: [V]?Int = none dist[src] = 0 // bare T lifts implicitly into ?T let via = dist[src] + 7 if dist[v] min= via: print("improved") // update and test whether the value changed let d = dist[v] ?? -1 // fallback; use parens when mixing ?? with + - * / % fn maybe() -> ?Int: 7 fn next_value() -> ?Int: let opt = maybe() let u = opt ?? return none // diverging RHS (return / break / continue) allowed let x = opt! // unwrap (traps on none; elided when flow-proven) let y = maybe()? // early-returns none from a fn returning ?U u + x + y print(next_value() ?? -1) ``` ### Lifting rules and guardrails - Arithmetic (`+`, `-`, `*`, `/`, `%`, `**`, unary `-`/`+`) and bitwise (`&`, `|`, `^`, `<<`, `>>`, `~`) operators lift over `?Int` and `?F64`, absorbing `none` (`none + w` and `none * 2` are `none`; division by zero still traps when both sides are present). - `min(a, b)` and `max(a, b)` skip `none`: `(T, ?T) -> T` and `(?T, ?T) -> ?T`. For three or more values, pass a list (`min([a, b, c])`). - `x min= cand` and `x max= cand` skip when `cand` is `none` — even when `x` is a plain `Int`! - Both updates return `Bool`: `true` exactly when the destination changes. Use `if best[v] min= via:` to enqueue a graph relaxation or update a DP witness only on improvement. Ties and `none` candidates return `false`; a present candidate improves an empty destination. - `==` and `!=` lift `T` to `?T` automatically (`if dq.last != x:`), while `<`, `<=`, `>`, `>=` never lift over `?T`. - `p ??= init` initializes `p` lazily when `none` and lends it mutably: `(adj[k] ??= []).push(x)`. - `?V + k`, `sum(gen)`, and compound `+=`/`-=` **never** lift over `?T`. - Neither `?T` nor `Mod

` implements `Ord`. To sort optionals, pass an explicit key such as `by: x => (x.d == none, x.d ?? 0)`. - When `none` means *invalid/impossible* rather than *+inf/-inf*, check explicitly instead of relying on `min=` skipping it: ```cp fn solve(child: Int) -> ?Int: if child >= 0: child else: none var best: ?Int = none for child in [3, -1, 4]: if let hit = solve(child): best min= hit else: best = none break print(best, none: "-1") ``` ## Records, structs, enums, and traits Define lightweight named tuples with `type`, stateful types with methods using `struct`, and algebraic sum types with `enum`: ```cp type Point = (x: Int, y: Int) struct Pt: x: Int, y: Int // one-line colon struct (commas separate fields) struct Seg: l: Int r: Int fn width(self) -> Int: self.r - self.l enum Event: Open(x: Int) Close(x: Int) Query(id: Int, x: Int) enum Dir = N | E | S | W // one-line plain enum ``` - **Records (`type`)** are structural and support both field names (`p.x`) and positional indexing (`p.0`). - **Structs and enums** are nominal. Seven core traits derive automatically whenever all fields support them: `Index`, `Seq`, `Eq`, `Ord`, `Hash`, `Show`, and `Read`. An enum orders by variant, in declaration order, then by the variant's fields, so `events.sort()` puts every `Open` before every `Close`. A written `impl` replaces a derived one everywhere: with `impl Read for Cell: fn read() -> Cell`, `let moves: [n]Move = read()` reads each `Cell` inside each `Move` through it. - Automatic tagged-enum input with `@tags("...")` is specified but not yet implemented. Use explicit character matching as shown in [I/O & formatting](/docs/guides/io-and-formatting). - **`for f in fields(x)`** runs its body once per field of a struct, record or tuple, in declaration order, with `f` that field; `for (a, b) in fields(x, y)` walks two values of one type in step. The loop is unrolled when the program is compiled, so each `f` has its own type, the body has no `break` or `continue`, and a generic fn can use it on whatever it is given: ```cp CP Lang 0.3 fn same(a: T, b: T) -> Int: var n = 0 for (x, y) in fields(a, b): if x == y: n += 1 n ``` On an enum value, `fields(e)` walks the payload of the variant `e` is (nothing for a variant without one); `fields(a, b)` runs only when both are the same variant. - **`P(e for f in fields(x))`** builds a struct field by field: `e` runs once per field, in order, expected to be that field's type, and gives it. `P(read() for _ in fields(P))` reads one (`fields(P)` names the type, so there is nothing to bind); `P(x + y for (x, y) in fields(a, b))` adds two. A struct with a `new` still goes through `new`. - Generic functions and types use angle brackets (`fn swap(mut a: T, mut b: T)`), with explicit type arguments at call sites when they cannot be inferred: `read<(Int, Int)>()`, or `f::()`. ## Control flow, pattern matching, and functions ```cp let x: Int = read() fn neg(): print("negative") fn zero(): print("zero") fn pos(): print("positive") if x < 0: neg() elif x == 0: zero() else: pos() let sign = if x >= 0: 1 else: -1 ``` ### Pattern matching (`match`) and `if let` / `while let` `match` is exhaustive and works as both a statement and an expression. In `if`, `elif`, and `while` headers, bind with `if let p = x` / `while let p = x` and chain extra bindings or boolean guards with `,` (`x is pat` stays for value position where a `Bool` is wanted): ```cp fn first() -> ?Int: 2 fn second(a: Int) -> ?Int: a + 1 if let a = first(), b = second(a) and a + b > 0: print(a + b) enum Event: Open(x: Int) Close(x: Int) Query(id: Int, x: Int) let ev = Query(0, 7) var active = 2 var ans: [0..1]Int = 0 match ev: Event.Open(x) => active += 1 Event.Close(x) => active -= 1 Event.Query(id, x) if active > 0 => ans[id] = active Event.Query(id, _) => ans[id] = 0 ``` ### Lazy parameters A parameter marked `lazy` has a nullary function type, and the caller writes the expression itself; the fn runs it by calling the parameter, zero or more times: ```cp fn or_else(a: ?T, lazy d: () -> T) -> T: if let v = a: return v d() fn solve(k: Int) -> Int = k * k let cached: ?Int = none print(or_else(cached, solve(4))) // `solve(4)` runs only because `cached` is none ``` A lambda `() => e` is accepted too. ### Variadic parameters A last positional parameter written `..xs: Ts` takes every remaining positional argument as one tuple; `Ts` is a type parameter, bound per call to the tuple's type, so the arguments can differ in type. Walk them with `fields`: ```cp fn show_line(..xs: Ts): for x in fields(xs): print(x) show_line(3, "abc", true) // Ts = (Int, Str, Bool) ``` For many arguments of one type, take a `List` and pass `[a, b, c]`. ### Loops, parallel assignment, and closures - **Counted and infinite loops:** `repeat n:` runs a body `n` times (sugar for `for _ in 0..n:`); `loop:` runs until `break` (sugar for `while true:`). - **Loop `else`:** `for` and `while` take an optional trailing `else:` at the loop's indentation that runs when no `break` left the loop (a labelled `break 'outer` skips inner `else:` blocks too). - **Filtered loops & comprehensions:** `for v in V if ok(v):` and `[f(v) for v in V if ok(v)]` (always use `if` for filters). Comprehensions and generator expressions (`sum(...)`, `[...]`) take a **single** `for` clause — for 2D loops, use nested `for r in Row:` / `for c in Col:` statements. - **Free math functions:** `abs(x)`, `min(a, b)`, `max(a, b)`, `gcd(a, b)`, `lcm(a, b)` are free functions, not methods on `Int` (write `abs(a - b)`, not `(a - b).abs()`). Power is `**` (`a ** b`, never `.pow`). - **Conditional expressions, `match` arms, & lambdas:** inline conditionals use `if cond: a else: b` (with colons — never `then` or Python's `a if cond else b`). Never leave `=`, `=>`, `and`, `or`, or binary operators at the end of a line (`E0102`): wrap multi-line expressions in parentheses `(...)`. Both `match` arms (`pat => expr`) and arrow lambdas (`x => expr`, `[V] v => expr`) take a **single value expression on the same line** (no `continue`/`break`/`return` after `=>`). For multi-statement bodies or loop control (`continue`/`break`), define a local `fn f(x: T) -> U:` or use `if`/`elif`/`else`. - **`mut` parameters vs local copies:** `fn f(mut x: T)` borrows `x` mutably from the caller and requires `f(mut arg)` at every call site (`E0402`). If you only want to reassign a local copy of a scalar parameter inside `f`, keep the parameter immutable (`fn f(x: Int)`) and bind `var cur = x` inside the body. - **Tuples, punning, & reserved keywords:** positional tuples `(Int, Int)` use `.0`, `.1`; named tuples `(a: Int, b: Int)` use `.a`, `.b` (not `.0`). When a named argument or record field has the same name as a variable in scope, write `f(moves:, cost:)` or `(val:, prev:)` as shorthand for `moves: moves` / `val: val`. Avoid reserved keywords as variable names — especially `use`, `type`, `in`, `match`, `domain`, `fn`, `let`, `var`. - **Index-value pairs:** For a list or string, iterate `i in 0..a.len` and access `a[i]` when you need both. - **Domains and containers:** `for v in V:` iterates a domain; `for v in V by k:` and `for v in V.rev by k:` step along a domain; `for x in a:` visits container elements. For a two-dimensional grid, use nested row/column loops. - **Modifiers:** `.rev` and `.step(k)` work on any range (`for i in (0..n).step(2).rev:`). - **Labeled exits:** `'outer: for r in Row: ... break 'outer` (or `continue 'outer`). - **Parallel assignment:** `(a, b) = (b, a % b)` evaluates the full right-hand side before assigning to the left. - **Closures & nested functions:** Short expressions use arrow lambdas (`x => x * 2`, `(a, b) => a + b`). Multi-line local helpers that mutate enclosing variables use plain nested `fn` declarations: ```cp var total = 0, step = 1 repeat 4: total += step step *= 2 loop: if total >= 15: break total += 1 let evens = [x for x in 0..8 if x % 2 == 0] print(total, evens) ``` ## Reserved keywords and decorators CP Lang keeps its surface small enough to remember during a contest — **34 keywords total**: - **Everyday keywords (30, including 3 literals):** `let`, `var`, `const`, `fn`, `struct`, `enum`, `domain`, `type`, `use`, `pub`, `if`, `elif`, `else`, `for`, `while`, `in`, `match`, `return`, `break`, `continue`, `and`, `or`, `not`, `assert`, `mut`, `self`, `unchecked`, `true`, `false`, `none`. - **Library-author keywords (4):** `trait`, `impl`, `lends`, `yield`. - **Contest decorators (7) + file directive (1):** `@memo`, `@alt`, `@tags`, `@gen`, `@check`, `@interactor`, `@grader`, plus `@!multitest`. - **Library-author decorators (4):** `@get`, `@test`, `@law`, `@on_unimplemented`. A trait's `@on_unimplemented("`\{T\}` can't be hashed; ...")` is the help a call shows when a type argument `T` has no `impl` of it. --- # Documentation URL: /docs CP Lang is in beta. Every example on this site carries a badge set by the compiler: **runs** means it runs today, **checks** means the checker accepts it but it doesn't run yet, and **0.3 spec** means it is written to the spec and the compiler doesn't accept it yet. ```cp input="3\n1 2 3\n" let n: 1..=2e5 = read() domain V = 1..=n let a: [V]Int = read() print(a.sum()) ``` --- # 0. Overview URL: /docs/ref/core/00-overview This is the normative specification ([source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/core/00-overview.md)). For a gentler introduction, start with the [guides](/docs/guides). CP Lang is a language for competitive programming that compiles to one C++17 file. Its mission is to minimize the time from an algorithmic idea to an accepted submission the contestant understands and trusts (`AGENTS.md`). This page is the model in one place; every claim points to the chapter that defines it. ## The model - **Types carry the facts a contestant already knows.** A domain `domain V = 1..=n` is a fresh index type, so vertices, edges, rows and columns cannot be mixed up; a range type `1..=1e9` is a contract that gives storage width, overflow proofs and input validation; `?T` is "maybe absent" with no sentinel and usually no extra bytes. (chapters 2-4) - **Values are owned or lent.** Heap values move, copies are `.clone()`, parameters are lent, `mut` marks mutation at both ends, and a lent value cannot outlive or race its source. There are no lifetimes in signatures except `lends`. (chapter 5) - **Sequences are generators and views.** A generator pushes elements to a loop body and allocates nothing; views (slices, `filter`, `map`) keep their source's keys; library operations ask for the weakest of six capabilities. (chapters 6-7) - **Operations are values.** `+`, `max`, `gcd` and user monoids are values with laws; segment trees, sparse tables, sliding windows, folds and convolutions take them and pick a documented specialization from the laws. (`lib/ops-ranges.md`) - **The stdlib has no privileges.** Everything it does, a user library can do; the list of powers is chapter 12. - **Costs are visible.** No-parenthesis members are O(1); anything that allocates, copies or traverses looks like it; `cpl explain` shows every implicit choice (widths, layouts, specializations, copies). - **Two builds, one meaning.** Checked builds trap on every unproven fact; release builds run no checks by default. Valid programs behave identically in both and in the interpreter; an invalid program in release gets whatever its C++ does, as hand-written C++ would. (chapter 9) ## A small program ``` domain V = 1..=read<1..=2e5>() let m = read<0..=2e5>() let g = Graph.undirected(read<[m](u: V, v: V, w: 1..=1e9)>()) let p = dijkstra(g, from: [(V.first!, 0)]) print(p.dist[V.last!] ?? -1) ``` Every fact is stated once: the vertex count bounds positions (4-byte storage), 1-based input converts at the reads, weights are validated and proven not to overflow a path sum of `2e5 * 1e9`, and an unreachable target is `None`, not `INF`. ## Layers - **Core**: syntax, types, ownership, control flow, traits, contexts, checks and lowering (chapters 1-13). - **Library**: `std/*.cp` signatures with documented costs, and the family chapters in `lib/`. - **Tools**: the `cpl` CLI, judge profiles, stress and shrinking, explain, trace and debugger, fmt and lint, LSP, bundler (`tools/`). A feature is not done until it works in every tool. ## Vocabulary | Word | Meaning | |---|---| | domain | a fresh index type with a count (`V`, `t.Pre`, `Dir`) | | position | an element index of a domain (`v: V`) | | cut | a boundary between positions (`V.cuts`, `Cut`); `Int(c)` counts positions before it | | range | `a..b` of positions or cuts; also a range type `lo..=hi` of integers | | key | what a sequence is indexed by; slices keep source keys | | view | a sequence built on another without copying (slice, `filter`) | | generator | a recipe that pushes elements to a loop body | | lend | a borrow of a value for as long as the borrower is used | | niche | a spare bit pattern of a type that encodes `None` or an enum tag | | law | a promised property of an operation, sampled by stress | --- # 1. Lexical structure and grammar URL: /docs/ref/core/01-lexical-grammar This is the normative specification ([source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/core/01-lexical-grammar.md)). For a gentler introduction, start with the [guides](/docs/guides). Status: draft for 0.3.0. Sources: decisions 10 (archived chapter `design/spec/10-syntax.md`), 20, 22, 70, 93, 98, 111, 124-137, 140. Where those disagree, the later decision wins and this chapter states the result. ## 1.1 Source text A source file is UTF-8. Bytes outside ASCII may appear only inside string literals and comments; anywhere else they are a lex error. `Char` and `Str` values are ASCII (decision 1.6), so a non-ASCII byte inside a `Char` or `Str` literal is an error too; only comments may carry other text. (R01.1.1) - `//` starts a comment that runs to the end of the line. There are no block comments. `#` is not a comment; the lexer says so and offers the fix. (R01.1.2) - `///` starts a doc comment attached to the next item. Doc comments are Markdown; the first sentence is the summary shown by hover and `cpl doc`. Labelled lines after the prose (`cost:`, `traps:`, `example:`, `empty:`, `ties:`, `order:`) state the facts every public library function documents (`spec/std/README.md`). (R01.1.3) ## 1.2 Layout Blocks are indentation-based and opened by a line ending in `:`. ``` fn dist(a: P, b: P) -> Int: abs(a.x - b.x) + abs(a.y - b.y) ``` - Indentation is spaces only; a tab in leading whitespace is an error. The width is free but must be consistent inside one block, and a dedent must land exactly on an enclosing level. (R01.2.1) - A logical line ends at a newline outside brackets. Inside `( )`, `[ ]` and `{ }` newlines and indentation are ignored, with one exception: a line that ends in `=>` (a block lambda) or in `:` (a bracketed `match`, `if` or `else` block) resumes layout until the matching dedent (decision 98). (R01.2.2) - A one-line body follows `:` or `=` on the same line. A deeper line after a one-line body is "unexpected indent", unless it is a continuation line (below), which extends that body. (R01.2.3) - **Continuation.** A line indented deeper than the previous logical line, where that line does not end in `:`, continues it when its first token is `.`, `??`, `and`, `or` or a binary operator. This is how method chains and fallbacks wrap without brackets: (R01.2.4) ``` let best = xs.filter(p) .map(f) .max() ?? 0 ``` - `;` separates simple statements on one line (`if c: a.push(x); continue`). It never ends a line or follows a block header. `{ ... }` is an inline expression block whose statements are separated by `;` and whose value is its last expression. (R01.2.5) - Trailing commas are allowed in every comma-separated list. (R01.2.6) ## 1.3 Names Identifiers are `[A-Za-z_][A-Za-z0-9_]*`. Case is part of the grammar: - Types, domains, traits, type parameters and enum variants are `PascalCase`: `Some(x)`, `None`, `Ev.Add(v)`, `Dir.L` (decision 157). `true` and `false` are lowercase literals. (R01.3.1) - Values, functions, fields and modules are `snake_case` or lower camel; a value binding with an uppercase first letter is an error ("values are lowercase; `N` would read as a type"). (R01.3.2) - So a pattern needs no lookup to read: a capitalized name is a variant or constant, a lowercase name binds. `match h: Big => ...` tests the variant; `match h: big => ...` binds `big`. (R01.3.3) - In an expression, `Name<` opens type arguments when `Name` is capitalized and what follows parses as type arguments closed by `>`, and `name<` (lowercase) when the closing `>` is immediately followed by `(`, as in `s.parse>()`. So `a < b` is a comparison and `SegTree<0..=4e9>(+, a)` needs no turbofish. A lowercase generic function takes its type arguments from the expected type, or explicitly as `read<[n]Int>()`. (R01.3.4) - `_` is the discard name in patterns and parameters. (R01.3.5) ### Reserved words The 33 keywords are: ``` let var const fn struct enum domain type use pub if elif else for while in match return break continue and or not assert mut self unchecked true false trait impl lends yield ``` `todo` is a primary expression and `context`, `marker` and `uses` are contextual words (R11.1.2, R09.1.3): each is a keyword only where the grammar expects it and an ordinary name elsewhere. `Some` and `None` are not reserved: they are the variants of `?T`, in the prelude like any other name, so a user enum may also have a `None` variant (`Side.None`). (R01.3.6) Contextual words are keywords only in the position shown and ordinary names elsewhere: | Word | Position | |---|---| | `is` | `x is pat` in value position (decision 111) | | `with` | `with ctx(...):` blocks and `@with` (chapter 9); record update `x with f: v` | | `yields` | `-> yields T` on a generator fn (chapter 6) | | `law` | inside a `trait` or `impl` body (chapter 8) | | `where` | trait bounds after a signature (chapter 8) | | `without` | row types `..R without (u, v)` (chapter 8) | | `mod`, `extern` | inline modules and judge-provided fns (chapter 11) | | `by` | range steps `0..n by 2` | | `of` | constrained strings `Str of "01?"` (chapter 2) | | `Self` | inside `trait` and `impl` bodies | `unchecked:` opens a block whose arithmetic and indexing checks are off in every build (chapter 9); it is a statement, never an expression. (R01.3.7) ## 1.4 Literals - **Integers**: decimal with `_` separators, `0x...`, `0b...`. Scientific literals that denote an exact integer are `Int`: `2e5`, `1e9 + 7`, `4e18`. A literal's type is the singleton range `v..=v`, which widens as arithmetic proceeds (chapter 3). (R01.4.1) - **Floats** need a fraction or a non-integer value: `0.5`, `1.5e-9`. `.5` and `5.` are errors. (R01.4.2) - **Chars**: `'c'`, exactly one ASCII character or one escape (`\n \t \r \0 \\ \' \xHH`, `HH <= 7F`). `'ab'` is an error that suggests `"ab"`. (R01.4.3) - **Strings**: `"..."` with the same escapes plus `\"`. Every string literal interpolates: `"Case #{t}: {ans}"`; `{{` and `}}` are literal braces; `r"..."` is raw (no escapes, no interpolation). Format specs follow a colon inside the braces: `"{x:.9}"`, `"{v: }"` (chapter 10). (R01.4.4) - `true`, `false`, `None`. - **Lists** `[a, b, c]`, **maps** `[k: v, k2: v2]` (`[:]` is empty), **tuples** `(a, b)`, **records** `(lo: 1, hi: n)`. (R01.4.5) - **Literal-union types** use literals as types: `'+' | '-'`, `"add" | "del"` (decision 135). `++` is a lex error ("CP Lang concatenates with `+`"). (R01.4.6) ## 1.5 Operators and precedence Tightest first: 1. postfix: `.f`, `.0`, calls `f(...)`, indexing `a[i]`, `!` (unwrap or trap), `?` (propagate `None`), `is pattern` (so `a + b is P` is `a + (b is P)`; parenthesize the left side) 2. `**` (right-associative; the right operand may start with unary `-`) 3. unary `-`, `+` (numeric only), `~` 4. `*`, `/`, `%` 5. `+`, `-` 6. `<<`, `>>` 7. `&` 8. `^` (xor only; power is `**`) 9. `|` 10. ranges `..`, `..=` (and the one-sided forms) 11. comparisons `< <= > >= == != in`, chainable in one direction only 12. `not` 13. `and` 14. `or` 15. `??` (right-associative, lazy right side) 16. lambdas `=>`, inline `if ... else ...` So `-x ** 2` is `-(x ** 2)`, `not a == b` is `not (a == b)`, and `s & (s << 1) == 0` is `(s & (s << 1)) == 0`. (R01.5.1) - `/` is floor division and `%` is never negative (decision 24). (R01.5.2) - Chained comparisons keep Python's meaning, each operand evaluated once, but only when every link points the same way: `0 <= i < j <= n` is legal; `a < b > c` and any chain containing `==` or `!=` is an error suggesting `and` (decision 130). (R01.5.3) - Operands and arguments evaluate left to right. Assignment evaluates the right side first, then the place (chapter 5). (R01.5.4) - `and`, `or`, `+`, `*`, `min`, `max`, `gcd`, `^`, `&`, `|` are also operation values (`xs.fold(or)`, `SegTree(max, a)`; `lib/ops-ranges.md`). `add` is the prelude name of `+` as a value: the same value, so `act: +` and `act: add` are one argument. (R01.5.5) - `??` written next to `+ - * / %` without parentheses is an error: `a ?? 0 + 1` must be written `(a ?? 0) + 1` or `a ?? (0 + 1)`, since either reading is a common slip. (R01.5.6) ## 1.6 Statements - `let p = e` binds immutably; `var p = e` mutably; `const N = e` is a compile-time constant. `let p: T = e` annotates. Several names may share a type: `let n, m: 1..=2e5 = read()`; `var a, b: Int = 0` fills each with the value. (R01.6.1) - `let p = e else: block` binds or runs the block, which must leave (`return`, `break`, `continue` or a trap). (R01.6.2) - `var` inside a pattern makes that one binding mutable: `for (var left, v) in items:`. (R01.6.3) - Assignment `place = e`, destructuring `(a, b) = (b, a)`, compound assignment `x op= e` for every binary operator and for `min=` / `max=`. Compound assignment is a statement, except that `min=` and `max=` used as a condition are `true` when the target strictly improved, including from `None` (decision 129): `if dist[v] min= dist[u] + w: parent[v] = u`. (R01.6.4) - `return e` exists for early exits; a block's value is its last expression. At top level `return` ends the program (or the test case under `@!multitest`). (R01.6.5) - `assert cond` and `assert cond, "message {x}"`: checked builds only, unless opted in for release (chapter 9). (R01.6.6) - `todo` is an expression of any type that traps when run; library stubs use it as a body. (R01.6.7) ## 1.7 Control flow ``` if c: a elif d: b else: e // inline form is an expression if let v = m.get(k), v > 0: ... // header binders, comma conditions while let x = q.pop(): ... for v in V: ... for i in V, j in V.after(i) if ok(i, j): ... // clauses nest; `if` filters 'outer: for r in R: for c in C: if g[r, c] == '#': break 'outer else: print("none") // loop else: runs when no break match op: Add(l, r) => st.apply(l..r, add(1)) Ask(i) => print(st[i]) match d: L => -1, R => 1 // one-line match ``` - `if let` / `while let` bind in headers; `x is pat` (with `and cond`) is the value-position form. `if x is p:` in a header gets a lint with a fix to the `let` form (decision 111). (R01.7.1) - `for` and `while` take an `else:` that runs when the loop ended without `break`; a labelled break from an inner loop skips the inner `else` (decision 125). Labels are `'name:` before the loop. (R01.7.2) - `match` is exhaustive over enums, literal unions, `Bool` and `?T`. Arms may have guards `pat if cond =>`. There are no custom patterns: a view is a method returning an enum (decision 132). (R01.7.3) - Loops over library generators support `break`, `continue`, `return`, labels and `else` exactly like built-in loops (decision 126). (R01.7.4) - `@!multitest` on its own line is the multitest divider: code above it runs once, code below runs per test case (decision 20; chapter 10). (R01.7.5) ## 1.8 Expressions - **Lambdas** `x => e`, `(a, b) => e`, `(d: Int, l: Low) => e`, `_ => e`, `(mut d, e) => d.unite(e.0, e.1)` (a `mut` parameter, as in `fn`), and block lambdas: a line ending in `=>` opens an indented body whose value is its last expression. A lambda body may be an assignment, and then returns nothing. A `let`-bound lambda may call itself (decision 127). (R01.8.1) - **Comprehensions** `[f(x) for x in xs if p(x)]` build a `List`, or an array when the expected type is `[D]T`. **Tables** `[D] i => e` build `[D]T` eagerly; `[(A, B)] (a, b) => e` and `[A, B]` are the same 2-D table. (R01.8.2) - **Record update** `e with f: v, g: w` and `(..e, f: v)` copy `e` with some fields replaced (decision 134, row types in chapter 8). (R01.8.3) - **Ranges** `a..b`, `a..=b`, `a..`, `..b`, `..=b`, `..` (the full range wherever a range is taken), steps `a..b by k`. (R01.8.4) - **Indexing** `a[i]`, `g[r, c]` (never `g[r][c]`); `a[i]` on `[I, J]T` is the row place. `a[l..r]` is a slice view keeping the source keys. (R01.8.5) - **Optional chaining**: `x?.f`, `f(x?)` propagate `None`; `x ?? y` falls back lazily; `x!` unwraps or traps with the source location. (R01.8.6) - Members without parentheses are O(1) (`xs.len`, `t.parent[v]`); anything that does work has parentheses (`g.transpose()`), decision 140. (R01.8.7) ## 1.9 Items ``` use std.segtree.{SegTree} // imports; prelude is implicit pub fn f(xs: [D]T, by: T -> K = id) -> ?D = todo struct Edge: u: V, v: V, w: Int // one-line struct struct Tally: var top = 0 // var fields may change total: Int = 0 fn add(mut self, x: Int): self.top max= x self.total += x enum Dir = L | R | U | D enum Ev: Add(v: V) Ask(l: V, r: V) trait Monoid(Op): @get fn id(self) -> T law left_id(x: T) = self.op(self.id, x) == x impl Monoid for MatMul: ... type Grid = [R, C]Char domain V = 1..=n // a fresh index type @memo(array) fn ways(i: V.cuts) -> Mod

: ... mod geometry: ... // inline module extern fn ask(i: Int) -> Int // provided by the judge ``` Decorators are `@name` or `@name(args)` on the next item; the set is closed and listed in §6.4, plus `@!multitest` as the one file directive. Types, domains and structs may be declared inside a function body and use its runtime domains (decision 136). (R01.9.1) ## 1.10 Grammar EBNF over the token stream. `NL` ends a logical line; `INDENT` and `DEDENT` come from layout. `block := ':' (simple_stmts NL | NL INDENT stmt+ DEDENT)`. On one line, `if c: s1 else: s2` (and `elif`) with simple statements is an `if_stmt`: the `NL` before `else` is optional when the whole statement fits on one line. In a type position, `[D]` is followed by a type, so `[V]-1e9..=1e9` is a range type whose ends may be signed. ```text file := (directive | item)* directive := '@!' NAME call_args? NL item := decorator* (fn_decl | struct_decl | enum_decl | trait_decl | impl_decl | type_decl | domain_decl | mod_decl | extern_decl | use_decl) | stmt decorator := '@' path call_args? NL? use_decl := 'pub'? 'use' path ('.' '{' NAME (',' NAME)* ','? '}')? NL fn_decl := 'pub'? 'fn' fn_name generics? '(' params? ')' ret? where? (block | '=' expr NL) fn_name := NAME | '(' param ')' BINOP '(' param ')' // operator fns ret := '->' ('yields' | 'lends' lend_src?)? type lend_src := '(' NAME (',' NAME)* ')' params := param (',' param)* (';' param (',' param)*)? ','? param := 'mut'? (pattern | 'self') (':' type)? ('=' expr)? | '..' NAME ':' TYPE_NAME // variadic tuple generics := '<' gparam (',' gparam)* ','? '>' gparam := 'domain'? TYPE_NAME (':' bound)? ('=' type)? | 'const' NAME ':' type bound := type ('+' type)* where := 'where' TYPE_NAME ':' bound (',' TYPE_NAME ':' bound)* struct_decl := 'pub'? 'struct' TYPE_NAME generics? (':' fields NL | ':' NL INDENT (field NL | fn_decl)+ DEDENT | NL) // bodyless: opaque fields := field (',' field)* field := 'var'? NAME (':' type)? ('=' expr)? enum_decl := 'pub'? 'enum' TYPE_NAME generics? ('=' NAME ('|' NAME)* NL | ':' NL INDENT (variant NL | fn_decl)+ DEDENT) variant := decorator* NAME ('(' fields ')')? trait_decl := 'pub'? 'trait' TYPE_NAME generics? ('(' bound ')')? ':' NL INDENT trait_item+ DEDENT trait_item := 'type' TYPE_NAME (':' bound)? NL | field NL | fn_sig NL | fn_decl | law law := 'law' NAME '(' params? ')' '=' expr NL impl_decl := 'impl' generics? bound ('for' type)? where? (':' NL INDENT (fn_decl | 'type' TYPE_NAME '=' type NL | law)+ DEDENT | NL) type_decl := 'pub'? 'type' TYPE_NAME generics? '=' type NL domain_decl := 'domain' TYPE_NAME '=' expr NL | 'let' '(' 'domain' TYPE_NAME (',' pattern)* ')' '=' expr NL mod_decl := 'pub'? 'mod' NAME ':' NL INDENT item+ DEDENT extern_decl := 'extern' 'fn' NAME '(' params? ')' ret? NL stmt := simple_stmts NL | compound simple_stmts:= simple (';' simple)* simple := let | assign | expr | 'return' expr? | 'break' LABEL? | 'continue' LABEL? | 'assert' expr (',' expr)? let := ('let' | 'var' | 'const') pattern (',' NAME)* (':' type)? '=' expr ('else' block)? assign := place ('=' | ASSIGN_OP | NAME '=') expr // `x min= y`, `x f= y` compound := if_stmt | for_stmt | while_stmt | match_stmt | with_stmt | unchecked | decorator* fn_decl if_stmt := 'if' cond block ('elif' cond block)* ('else' block)? cond := 'let' pattern '=' expr (',' cond)* | expr (',' cond)* | place ('min=' | 'max=') expr // true when improved (R01.6.4) for_stmt := (LABEL ':')? 'for' clause (',' clause)* block ('else' block)? clause := pattern 'in' expr ('if' expr)? while_stmt := (LABEL ':')? 'while' cond block ('else' block)? match_stmt := 'match' expr ':' (arm (',' arm)* NL | NL INDENT (arm NL)+ DEDENT) arm := pattern ('if' expr)? '=>' (expr | assign | NL INDENT stmt+ DEDENT) with_stmt := 'with' call (',' call)* block unchecked := 'unchecked' block pattern := '_' | 'var'? NAME | literal | range_pat | '(' pattern (',' pattern)* ','? ')' | '(' NAME ':' pattern (',' NAME ':' pattern)* (',' '..')? ')' | path ('(' pattern (',' pattern)* ')')? // variants, V(j) | pattern '|' pattern range_pat := literal ('..' | '..=') literal type := '?' type | '[' dims ']' type | '(' type (',' type)* ','? ')' | '(' NAME ':' type (',' NAME ':' type)* (',' '..' TYPE_NAME ('without' '(' NAME (',' NAME)* ')')?)? ')' // records, rows | path generic_args? | range_type | literal ('|' literal)* | '(' (type (',' type)*)? ')' '->' type // fn types | type 'of' STRING dims := type (',' type)* | '(' type (',' type)* ')' | expr range_type := expr? ('..' | '..=') expr? expr := lambda | if_expr | binary lambda := lparams '=>' (expr | assign | NL INDENT stmt* expr? DEDENT) lparams := NAME | '_' | '(' (param (',' param)*)? ')' ('->' type)? if_expr := 'if' cond ':' expr ('elif' cond ':' expr)* 'else' ':' expr binary := the operators of 1.5 over unary; `not` is the prefix operator at level 12, so `not a == b` is `not (a == b)` unary := ('-' | '+' | '~') unary | power power := postfix ('**' unary)? postfix := primary ('.' NAME | '.' INT | call_args | '[' args ']' | '!' | '?' | 'is' pattern | 'with' NAME ':' expr (',' NAME ':' expr)*)* call_args := '(' (arg (',' arg)*)? ','? ')' arg := expr | NAME ':' expr | 'mut' place primary := literal | NAME | path generic_args? | '(' expr ')' | tuple | record | list | map | comprehension | table | '{' block_expr '}' | 'todo' | BINOP // `+` as an op value ``` Call arguments: positional first, named after in any order, each parameter at most once; parameters after `;` are named-only. A `mut` parameter is marked `mut` at the call too (`link(mut d, a, b)`), except for the receiver of a method call. (R01.10.1) ## 1.11 Rejected spellings Each of these gets an error with a machine-applicable fix: (R01.11.1) | Written | Write instead | Decision | |---|---|---| | `#` comment | `//` | 10.1 | | `xs ++ ys` | `xs + ys` | 98 | | `for x in xs where p` | `for x in xs if p` | 70, 93 | | `x.pow(k)`, `x ^ k` meaning power | `x ** k` | 70 | | `xs.len()` on a getter | `xs.len` | 93 | | `if x is p:` header | `if let p = x:` | 111 | | `{k: v}` map literal | `[k: v]` | 135 | | `[x; n]` | `[x] * n` or a typed `[n]T` | 135 | | `(let a = ...; e)` | a block lambda or `{ let a = ...; e }` | 135 | | `fn f() -> T =` then an indented block | `fn f() -> T:` | 136 | | `--- multitest ---` | `@!multitest` | 93 | | `defer` and other v2.1 words | as the error says | 19 | --- # 2. Values and types URL: /docs/ref/core/02-values-types This is the normative specification ([source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/core/02-values-types.md)). For a gentler introduction, start with the [guides](/docs/guides). Status: draft for 0.3.0. Numbers, ranges, widths, niches and layout are chapter 3; positions, cuts and domains chapter 4; ownership chapter 5; traits, generics and row types chapter 8. Sources: decisions 1.x, 2.x, 33, 88, 124, 128, 131, 132, 134-136, 141, 149; archived `design/spec/11-13, 23`. ## 2.1 The kinds of value Every value is one of: - a **plain value**: numbers, `Bool`, `Char`, positions and cuts of a domain, `?T` of a plain `T`, and tuples, records, structs and enums built only from plain values. Plain values copy on assignment and fit in registers or a few words. (R02.1.1) - a **heap value**: `List`, `Str`, `[D]T` arrays, `Map`, `Set`, every library container, and any struct holding one. Heap values move on assignment and are copied only by `.clone()` (decision 128). (R02.1.2) - a **function value**: `fn` items, lambdas and operation values. They are zero-size when they capture nothing and are always inlined; there is no boxed function type (chapter 13). (R02.1.3) - a **generator value**: a recipe that pushes elements to a loop body (chapter 6, `07-sequences.md`). Whether a value is owned or lent is not part of its type (chapter 5). (R02.1.4) ## 2.2 Scalars | Type | Values | Notes | |---|---|---| | `Int` | `-(2^63 - 1) ..= 2^63 - 1` | the default integer; `Int.MIN` is one above `-2^63`, which is `?Int`'s `None` (decision 49) | | range types `lo..=hi`, `lo..hi`, `lo..`, `..=hi` | the integers in the range | an `Int` with a contract and a storage width (chapter 3) | | `U64` | `0 ..= 2^64 - 1`, wrapping | hashes, masks, bit tricks | | `I128` | signed 128-bit | products past `Int` | | `F64` | IEEE double | `==` is exact; `close(a, b, eps:)` is the tolerant compare | | `Bool` | `true`, `false` | 1 byte; packed in `Bits` | | `Char` | ASCII `0..=127` | 1 byte; `Int(c)`, `Char(i)`, `c.is_digit`, ... | | `()` | the unit value | what statements and `print` return | | `Never` | no values | the type of `return`, `break`, traps, `todo` | There are exactly four number types (decision 1.7). Narrow storage is a range type, never a separate integer type: `[V]0..=255` stores one byte per element. (R02.2.1) Literal-union types are scalars too: `'+' | '-'` or `"add" | "del"` has exactly those values, reads validate them, and `match` is exhaustive over them (decision 135). (R02.2.2) ## 2.3 Strings `Str` is a flat sequence of `Char` indexed by `0..len`, with the sequence capabilities of chapter 7 (it is `Indexed`, `Sized` and `Bidir`). Slices keep source positions, as for every sequence (`04b-keys.md`). (R02.3.1) - `Str of "01?"` is a string whose characters come from the literal's alphabet. The alphabet is a domain, so `[Alpha]Int` is a table over it and reads validate it. `Str(len: 1..=2e5)` bounds the length, checked on read like a range (decision 134). (R02.3.2) - `+` concatenates (allocating; the cost is visible as a new value); `s.push(c)` appends in place. (R02.3.3) - Interpolation `"{x}"` formats through the `Print` trait (chapter 10). ## 2.4 Optionals `?T` is `T` or `None`. - `x.is_some_and(p)` tests a value and a predicate at once (`false` on `None`); `x.is_none_or(p)` is its dual (`true` on `None`). `x.map(f)` and `x.and_then(f)` (for `f: T -> ?U`) transform the value and keep `None`. (R02.4.1) - `T` converts to `?T` implicitly; the other way is explicit: `x ?? d` (lazy fallback), `x!` (unwrap or trap, naming the place), `if let`, `while let`, `let ... else`, `match`. (R02.4.2) - When `T` has a spare value (a niche), `?T` takes no more bytes than `T` (chapter 3). Otherwise it adds a flag byte, rounded to alignment. `?(?T)` is legal and adds a flag around `?T`. (R02.4.3) - **Arithmetic and bitwise operators lift**: `?Int + Int` is `?Int`, `None` if either side is. Lifting is three ordinary impls, not a language rule (`impl Add for ?T`). (R02.4.4) - **Ordering does not lift**: `?T` is not `Ord`, so `dp[j] + c < best` with an optional left side is an error, never a silent `false`. `==` is structural (`None == None`). (R02.4.5) - `min`, `max`, `min=` and `max=` treat `None` as the identity: a `None` target takes the right side, a `None` right side changes nothing. With lifted arithmetic this is "skip unreachable states": (R02.4.6) ``` dist[v] min= dist[u] + w // dist[u] none: nothing happens ``` - **Postfix `x?`** propagates where operators don't reach: `a[x?]`, `f(x?)`, `x?.len`, `(dp[j]? + w, j)`. The extent is the nearest enclosing parenthesized group, call argument, left operand of `??`, lambda or `fn ... =` body, or statement right-hand side. A `?` in an `if` or `while` condition is an error (write `... ?? false`), and a `?` whose result is dropped is an error. `?` is never control flow; an early exit is `let x = e else: return None` (chapter 6). (R02.4.7) - `x!` is the `Unwrap` trait. `?T`, `[D]?T` and `List` implement it; the array forms check every element in one pass and trap naming the first gap ("depth[17] is None"). This ends a fill phase: `let depth = depth!`. `.all_some()` is the non-trapping form. (R02.4.8) ## 2.5 Tuples and records - Tuples `(Int, V)` are positional; `.0`, `.1` and destructuring read them. (R02.5.1) - Records `(lo: Int, hi: V)` are anonymous structs with named fields. Two record types are equal when they have the same field names and types in the same order. Records are structural: a record with fields `.to` and `.w` satisfies field traits such as `Target` and `Weighted` without an impl (chapter 8). (R02.5.2) - Record update copies with replacements: `a with to: u` or `(..a, to: u)`. (R02.5.3) - Row types `R: (u: V, v: V, ..)` accept any record with at least those fields, and `..R without (u, v)` names the rest. There is no record subtyping and no implicit field dropping: a function that wants fewer fields says so with a row bound (chapter 8). (R02.5.4) ## 2.6 Structs ``` struct Edge: u: V, v: V, w: Int struct Tally: var top = 0 // typed by its default var sum = 0 name: Str = "" fn add(mut self, x: Int): self.top max= x self.sum += x ``` - Fields are fixed after construction unless declared `var`; assigning a non-`var` field is an error naming the field (decision 136). (R02.6.1) - Constructors are generated: `Edge(a, b, 5)` or `Edge(u: a, v: b, w: 5)`; fields with defaults may be omitted (decision 134). A custom constructor is a static fn (`Graph.read()`). There are no constructor side effects and no destructors. (R02.6.2) - **Two kinds of constructor, one rule each.** A generated constructor (`Edge(a, b, 5)`, a struct literal) stores its arguments, so it takes them by value: an owned heap argument moves in, a lent one makes the struct lent. A custom constructor is an ordinary static fn (`SegTree(max, a)` is `SegTree.new(max, a)`, `Rooted(g, root: r)`): its parameters are lent for the call and its result is owned unless the signature says `lends` (chapter 5, decision 147). The cost rule tells them apart: a custom constructor that keeps data copies it (O(n), documented) or says `lends`. (R02.6.3) - `struct List` with no body is opaque: its fields are private to its module. A struct body may hold methods with `self` or `mut self`. (R02.6.4) - Named structs satisfy traits only through `impl`, including field traits (`impl Target for Edge` with no body when the field exists). (R02.6.5) - `@get` on a read-only method whose other parameters all have defaults lets it be called without parentheses (`v.next` is `v.next(1)`); it must be O(1) (decision 140). (R02.6.6) - Storage may reorder fields to remove padding; source order is what constructors, patterns and printing use (chapter 3). (R02.6.7) ## 2.7 Enums ``` enum Dir = L | R | U | D // payload-free: an index type enum Ev: Add(v: V) Ask(l: V, r: V) fn is_query(self) -> Bool = self is Ask ``` - Variants are `PascalCase` names in their enum's scope, like `Some` and `None` of `?T` (decision 157). Context resolves bare variant names in patterns and where the expected type is the enum; a lowercase name in a pattern always binds. (R02.7.1) - `@tag(lit)` on a variant names the token it reads and prints as (`@tag("Q") Ask(h: Int)`, `@tag(1) Add(l: V, r: V)`); without it the token is the variant's name. Tags are distinct within the enum (E0407). (R02.7.2) - A payload-free enum is a domain: `[Dir]Int` is a table, `for d in Dir` walks it. (R02.7.3) - `match` is exhaustive. Patterns match only the stored shape; there are no user-defined patterns (decision 132). (R02.7.4) - Layout uses niche filling, so `Ev` is 8 bytes with no tag when `V` positions are 4 bytes (chapter 3). (R02.7.5) ## 2.8 Arrays and lists - `[D]T` is a fixed-size array indexed by domain `D` (positions of `D`, never raw `Int`). `[R, C]T` is a dense row-major 2-D array indexed `g[r, c]`; `[(R, C)]T` is the same type. `g[r]` is the row place. A counted dimension `[n]T` means `[0..n]T`. (R02.8.1) - `List` grows, is indexed by `0..len` positions, and its slices keep source positions. (R02.8.2) - `[D]T` arrays are built by tables (`[V] v => 0`), typed reads (`read<[V]Int>()`), comprehensions with an expected array type, or `[D].filled(x)`, or a scalar `x: T` where a `[D]T` is expected (a fill, R04.4.27); every element is initialized. (R02.8.3) - `xs[i]` on a heap element lends it (`let row = rows[i]`); on a plain element it copies. (R02.8.4) - Large arrays never live on the C++ stack (chapter 13). (R02.8.5) ## 2.9 Fresh types: domains and runtime-parameterized types A binding can introduce a type whose identity is the binding: ``` domain V = 1..=read<1..=2e5>() let (domain Piece, piece_of) = t.components(without: c) type Z = Mod(read()) // runtime modulus ``` - Two fresh types are never equal, even from the same expression. (R02.9.1) - A fresh type is block-scoped. A value whose type mentions it cannot leave the block by `return`, by assignment to an outer `var`, by a stored closure, by a per-program binding (so a position cannot leak into the next test case), or by a field of a struct declared outside the block. Passing it to a call is always fine. (R02.9.2) - A function may return a fresh type existentially: `fn components(...) -> (domain P, [V]P)`; the caller binds it with `let (domain P, ...) = ...`. User code can write such functions: the body returns a tuple whose `domain` slot is a domain declared in the body, `(J, [J] j => 0)`. A struct return may leave a domain parameter as `_`, `-> Rooted`: the body's value fixes it, and the caller reads it as a member, `t.Pre`. (R02.9.3) - A fresh type carries runtime data (a domain's count, a modulus) in one static slot per declaration site, saved and restored when a recursive block re-enters. Generic code reads the slot; nothing is passed hidden. A compile-time constant specializes the slot away. (R02.9.4) - `V.count` is typed by the declared range, which is where storage widths and overflow proofs come from. (R02.9.5) - Product domains `domain State = (V, K)` and disjoint unions `domain Node = In + Out` are domains too (decisions 2.x, 88). Written inline, `(V, K)` is the anonymous product domain, the same one that `[V, K]T` is indexed by: `(V, V).all((u, v) => d[u, v] == d[v, u])` (decision 159). (R02.9.6) ## 2.10 Type inference - Inference is local. Siblings in one expression (list elements, `if`/`else` branches, `match` arms, comprehension results) are unified before generics are fixed, with `None` joining `T` to `?T`. Inference never looks at later statements: `var x = None` followed by `x = 3` is an error asking for `?Int` at the declaration (decision 131). (R02.10.1) - `let` keeps the computed range of its initializer; an unannotated `var` widens to `Int`; `var x: lo..=hi` checks each assignment. Range inference goes through arithmetic on `let`s, runs no loop fixpoints and crosses no calls. (R02.10.2) - Function signatures are written in full except that a single-capital type parameter used in a parameter type may be left undeclared (`fn peel(s: [D]Bool)`). (R02.10.3) ## 2.11 Never implicit - No implicit numeric conversions except into a wider range of the same type and `T` into `?T`. `Int` to `F64` is `F64(x)`; `F64` to `Int` is `x.floor()`, `x.round()` or `Int(x)` (truncating, documented). (R02.11.1) - No implicit copies of heap values (`.clone()`), no implicit allocation behind an O(1)-looking member, no implicit `Int` to position (`V(x)` traps out of range; `V.at(x)` is `?V`). (R02.11.2) - No inheritance, no subtyping, no overloading by argument type (decision 127), no user-defined implicit conversions. (R02.11.3) --- # 3. Numbers, widths and layout URL: /docs/ref/core/03-numbers-layout This is the normative specification ([source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/core/03-numbers-layout.md)). For a gentler introduction, start with the [guides](/docs/guides). Status: draft for 0.3.0, aligned with Ryan 2026-11-21 (decision 149). Scope: how numbers stay small in memory without the contestant thinking about bytes, and how `?T` costs nothing for ints, structs, records, enums and arrays. Modular arithmetic, floats and overflow semantics are summarized where they touch layout; their detailed rules stay in `design/spec/11-types.md`. ## The model in one paragraph **Values compute in 64 bits; storage takes the fewest bytes the type allows.** A local `Int` lives in a register, where width is free, so locals and arithmetic are always `Int` (i64) and nobody tunes them. Bytes matter only where values are stored many times: arrays, lists, struct fields, tables inside library structures. There, the storage width comes from the type you already wrote for a different reason: a domain (`[V]T`, `V` positions), a range from the statement (`read<1..=1e9>`), a `Mod

`, a `Bool`. Every type also has a set of **spare values** it never holds (`Int.MIN`, `hi + 1` for a range, `P` for `Mod

`, 2 for `Bool`); `?T` stores `None` in one of them, so it is as wide as `T`. A struct's spare values are its fields' spare values, so `?Edge` is as wide as `Edge` with no annotation. Both choices are automatic only because they never lose (same operations, never more bytes, never slower), and `cpl explain` prints every layout. ## 1. Where widths come from | Written | Storage | Why it is the type you'd write anyway | |---|---|---| | `Int`, no bound | 8 bytes | the default; nothing is guessed | | `lo..=hi` (static ends) | narrowest of u8/u16/u32/u64 (i8.. when `lo < 0`) that holds the range; `?` adds a byte only when no spare is left (`0..=255`) | statement bounds: `read<[V]1..=1e9>` | | `0..=V.count`, `1..=V.count` | as `V`'s positions | counts, sizes, depths | | a domain position `V` | narrowest that holds `V.count + 1` values | every index | | `Mod

` | u32 when `P < 2^31`, else u64 | the modulus | | `Bool` | 1 byte; `Bits` when you ask for bits | | | `Char` | 1 byte, ASCII `0..=127` | strings and grids | | `U64`, `I128` | exactly that | hashes and bit tricks (wrapping `U64`); products past i64 (`I128`) | | `F64` | 8 bytes | | - **Domain widths follow the static bound of the count.** `let n = read<1..=2e5>(); domain V = 0..n` gives 4-byte positions; `n: 1..=5000` gives 2-byte positions. Every `[V]V` parent array, `List` stack and `[V]0..=V.count` size array shrinks with it. (R03.1.1) - **Locals never narrow.** `let x: 0..=1e9 = ...` is a contract checked at assignment, but it lives in an i64 register. Narrowing a local saves nothing and costs conversions. (R03.1.2) - **Struct fields need static bounds** (unchanged): layout never depends on input. A field may be `V` (a domain position), since the domain's width bound is static. (R03.1.3) - **Loads widen, stores check.** Reading `a[i]` from a `[V]0..=1e9` is one zero-extending load; arithmetic is in `Int`, so `a[i] * a[j]` can't overflow 32 bits. Storing into a range-typed slot checks the range unless the checker proves it (`a[i] = a[i] % 7` needs no check). A range type is a contract: `cpl run` and checked builds trap on a violation; release builds don't check (decision 100), the same deal as `Int` overflow, so valid programs pay nothing on the judge. (R03.1.4) - **No `I32`, `U32` or `U8`.** A narrow slot is a range: `[V]0..=255` is one byte per element, `[V]0..=4e9` four. Decision 1.7 keeps the number types to `Int`, `U64`, `I128` and `F64`; a byte of text is `Char`. (R03.1.5) - **Narrow arithmetic when proven.** Semantically every operation is in `Int`. When the range proof shows an expression and its operands fit in 32 bits (`a[i] + b[i]` with both `0..=1e9` is at most `2e9`, a u32), the C++ computes it in 32 bits. Same answer, never slower, and twice the lanes when the loop vectorizes, so it majorizes; `cpl explain` marks it. (R03.1.6) Why this split: in registers, 64-bit `+ - * < &` cost the same as 32-bit on every judge CPU; only division by a runtime value is slower on older Intel. Width costs in memory (half the values per cache line, MLE) and in SIMD (4 i64 lanes vs 8 i32 per 256-bit register). So locals stay `Int`, storage narrows, and vectorizable arithmetic narrows only when proven. ### Ops decide what a structure stores Generic structures store their element type, so the narrow width flows through `SegTree`, `Heap`, `List`, `Dsu` with no extra syntax. The fold op decides the element type of the folds: | Structure | `a: [V]0..=1e9` stores | Why | |---|---|---| | `SegTree(max, a)` | 4-byte nodes | `max` is `Selective`: the result is one of the inputs, so it stays in `0..=1e9` | | `SegTree(+, a)` | 8-byte nodes | `+` is not closed on a range; with `n <= 2e5` sums reach `2e14`, so `T` is `Int` | | `SegTree(+, b)`, `b: [V]1..=1e4`, `n <= 2e5` | 4-byte nodes | a node sums at most `V.count` inputs: `0..=2e9`, proven | | `SegTree<0..=4e9>(+, a)` | 4-byte nodes | you named the node type; node writes are range stores | | `SegTree(+, a.map(Z))` | 4-byte nodes | `Mod

` is closed under `+` | | `Prefix(+, a)` | `[V.cuts]Int` | sums | | `Heap(by: .d)` of `(d: Int, v: V)` | 16 bytes (12 + padding) | each field at its own width | This is the law machinery of round 5 doing layout work: `Selective` already promised "returns one of its operands", which is exactly the fact that keeps a range closed. `+` gets the same treatment from its interval rule: with `N` the static bound of `V.count`, a fold of at most `N` inputs in `lo..=hi` lies in `min(0, N*lo) ..= max(0, N*hi)`, and the node type narrows when that fits. The bound comes from the static bound of `V.count`, so it holds for every input; with `act:` or point writes of unbounded values there is no bound and nodes stay `Int`. To force a width, name the type parameter: `SegTree<0..=4e9>(+, a)`. Every node write is then a range store under decision 148: checked builds trap with the node and the value, release truncates. (R03.1.7) ### Seeing and steering it - `cpl explain` lists every array, list and structure with its element layout and its peak bytes at the input bounds, e.g. `dist: [V]?Int, 8 B, 1.6 MB at n = 2e5`. - A static peak above the judge profile's memory limit is an error (E0904) naming the three largest arrays. (R03.1.9) - **Lint `wide_array`**: an array with a static size of at least 1e6 whose element type is `Int` while every value written into it has a narrower static range (a read, a domain position, a constant, `min`/`max` of those). It suggests the annotation, e.g. `[V]0..=1e9`. Purely local: it looks only at the writes in the same function. (R03.1.8) - Override with an explicit type in either direction: `[V]Int` widens, `[V]0..=4e9` stores 4 bytes. - **The editor shows the same facts** from the same computation: - hover on a type or variable gives its size, field storage order, padding and where `None` lives (`?Edge 8 B: None = all-ones in to`); - an inlay hint after each array or structure declaration gives element size and peak bytes at the input bounds (`8 B × 2e5 = 1.6 MB`); - a code lens at the top of the file gives total static peak against the profile's limit; `wide_array` and padding over 20% come with quick fixes. ## 2. Spare values Every type has a fixed set of **spare values**: bit patterns of its storage that no valid value uses. The set is a property of the type, never of a use, so two `?Edge`s always agree on layout. (R03.2.1) | Type | Spare values | `None` is | |---|---|---| | `Int` | `INT64_MIN` (`Int` is `-(2^63-1)..=2^63-1`) | `INT64_MIN` | | `lo..=hi` in width W | every W value outside `lo..=hi` | `hi + 1` if it fits, else `lo - 1` | | domain position `V` | indices `>= V.count` | the all-ones pattern | | `Mod

` | `P ..` up to the width | `P` | | `Bool` | 2..=255 | 2 | | unit `enum` with k variants | k..=255 | k | | `F64` | quiet-NaN payloads (NaN traps in checked runs) | one fixed payload | | `Char` | 128..=255 | 128 | | `U64`, `I128` | none | needs a flag | | `?T` | `T`'s spares minus the one `None` took | | ### Structs, records and tuples **`?S` borrows the first field, in declaration order, that has a spare value.** It writes `None` into that field and leaves the others undefined. So a struct of `Int`s has a niche because `Int` has one: (R03.2.2) ``` struct Edge: to: V, w: Int // 4 + 8 -> 16 B (padded) var best: [V]?Edge = [V].filled(None) // 16 B per slot, not 24 var span: ?(lo: Int, hi: Int) = None // 16 B: None lives in lo ``` - Records and tuples follow the same rule, since they are structs without names. - Nesting is free while spares remain: `?(?Int)`, a `[V]?Edge` inside a `?Paths`, `Dsu` parents stored as `[V]?V`. - **No user `Niche` trait** (decision 28.10). A library could name a value its own code later produces, turning a wrong `None` into silent corruption. Every struct that has a spare value already has one in a field, and a range type on one field is how you give it one: `struct H: h: U64, len: 0..=1e6` puts `?H` in `len`. (R03.2.3) ### Enums with payloads The tag goes into a spare value when that is free; otherwise it is a byte: - **One payload variant plus k unit variants** (`Option`-like: `Cell` with variants `Wall`, `Empty` and `Box(id: V)`): the unit variants take k spare values of the payload. `Cell` is 4 bytes. (R03.2.4) - **Several payload variants:** the largest variant (first on a tie) sets the layout. Every other variant is one spare value of a single field of it, the first field in declaration order with enough spares, provided that variant's own fields fit in the bytes outside that field. `Ev` with variants `Add(v: V)` and `Ask(l: V, r: V)` is 8 bytes: `Add` keeps `v` in `l`'s slot and writes all-ones into `r`'s slot, so a valid `r` means `Ask`. `?Ev` takes another spare of `r` and is also 8. (R03.2.5) - **Otherwise a tag byte** beside the largest payload, rounded up to alignment: when no field has enough spares (every bit pattern is a valid value) or a smaller variant can't fit around the field holding them. (R03.2.6) - The rule is Rust's niche filling, restricted to "first field with enough spares", so it is predictable without reading the compiler; `cpl explain` prints the encoding. ### Arrays of optionals `[V]?T` is `[V]T` with spares wherever `T` has one: the distance array `[V]?Int` is 8 bytes per vertex, `[V]?V` parents 4 bytes. When `T` has no spare (`[V]?U64`), the flag is stored inline next to each element. The compiler never splits it into a side bitset on its own: that would be smaller but costs a second load per access, so it doesn't majorize. Ask for it with `Opt` (a library struct of `[V]T` plus `Bits`) if memory is the limit. (R03.2.7) ### Field order Storage order is chosen to minimize padding (largest alignment first, then declaration order); visible order (constructors, patterns, `print`, derives, `..R` rows) stays declaration order. Nothing in the language observes addresses, so reordering never changes behaviour, and it only removes padding. A struct passed to `@cpp` code keeps declaration order, since C++ would see the storage. `cpl explain` shows the storage order. (R03.2.8) ### Cache layout Width is half of cache behaviour; layout is the other half. The defaults already favour locality: narrow storage packs more values per 64-byte line, `Graph` is CSR (a vertex's arcs are contiguous), trees reorder by `t.Pre` (subtrees are ranges, heavy chains are runs), segment trees are one flat array, and niches mean `?T` never costs a second miss on a flag array. Padding stays when a struct's fields don't fill its alignment (`(d: Int, v: V)` is 12 bytes of data in 16), as in C++. Two explicit fixes, neither automatic because neither is never-worse: | Spelling | Bytes | Trade | |---|---|---| | `Packed` (decision 1.2) | data only | unaligned loads; some elements straddle a line | | `layout: columns` on `[V]S`, `List`, `Heap` | data only | one array per field: a scan or sift touching one field reads only that column; touching all fields reads several lines | `cpl explain` flags any structure above 1 MB whose padding exceeds 20% of its element and names both fixes. ## 3. Operations on niche types - **Testing `None` is one compare** with the fixed pattern. (R03.3.1) - **`max=` on `?Int` is branch-free**: `INT64_MIN` is below every `Int`, so `None` is already the identity of `max` (the tropical rule in decision 1.3). `min=` on `?Int` compiles to one compare and a conditional move. (R03.3.2) - **Producing a spare value is an overflow.** `Int` arithmetic that lands on `INT64_MIN` traps in debug like any overflow; in release it is part of the wrap contract (a wrapped value may read as `None`). An out-of-range store is the same: checked builds trap before it writes a spare; release truncates, and the result may read as `None`. (R03.3.3) - **Reading input** rejects a value equal to a spare (`read` of `-9223372036854775808` is an input error naming the bound). (R03.3.4) - **Generic code** sees no difference: `?T` inside `SegTree` or a user struct gets `T`'s layout after monomorphization. ## 4. Overflow, in one table Ranges carry the proofs; the build decides what an unproven step does. **The rule for every check.** On the judge only valid programs matter, so release optimizes for them: no runtime check is on by default, and a wrong program gets a wrong answer. Checked builds (`cpl run`, stress, `-DLOCAL`) trap on every violation, so bugs show up before submission. The emitted C++ still has no undefined behaviour (wrapping goes through unsigned casts, which compile to the same instructions), so `-O2` never miscompiles the valid paths around a bug. To keep a check on the judge, opt in: `with checks(ranges: on, overflow: on)` on a block or file, or `release_checks:` in the judge profile. (R03.4.1) | Situation | Debug and `cpl run` | Release on the judge | |---|---|---| | `Int` arithmetic proven in range | no check | no check | | `Int` arithmetic unproven | trap with values | wraps | | store into a range type, unproven | trap | no check: truncates to the width | | `U64` | wraps | wraps | | `I128` arithmetic unproven | trap with values | wraps | | `wrapping_add` and friends | wraps | wraps | | result range exceeds i64 (`1..=1e9` cubed) | the result is plain `Int`; overflow checks apply | | Proofs are intraprocedural interval arithmetic on `let`s and declared ranges (already decided); nothing crosses calls, so compile time stays linear. (R03.4.2) ## 5. Modular numbers `Mod

` is stored in `0..P`, so it is 4 bytes for every common prime, `?Mod

` is free (`P` is spare) and `SegTree(+, a.map(Z))` stores 4-byte nodes. Multiplication widens to u64 (or `I128` for moduli above `2^32`, which the profile must allow). A runtime modulus is a scoped type (`Mod

` with `p` read once) using Barrett reduction, one local edit from the constant form. (R03.5.1) ## 6. Examples ``` let n = read<1..=2e5>() domain V = 0..n let a = read<[V]1..=1e9>() // 4 B per element var par: [V]?V = [V].filled(None) // 4 B, None = all ones var dist: [V]?Int = [V].filled(None) // 8 B, None = INT64_MIN var mx = SegTree(max, a) // 4 B nodes: max is Selective var sm = SegTree(+, a) // 8 B nodes: sums are Int struct Item: w: 1..=1e9, v: 1..=1e9, id: V // 12 B, ?Item 12 B ``` `cpl explain` on this prints, per line, the storage and the reason ("`a`: u32, from `1..=1e9`; spare `1e9 + 1`"). ## 7. What this needs - Core: storage width for static range types, domain positions and domain-relative ranges (implemented for 1D and nested arrays); niche borrowing for structs (28.10, implemented for `Int` and position fields); spare-value niches for enums, `Bool`, `Mod`, ranges and records (codegen debt); padding-minimizing field order (new). - Library: `Opt` (new), `Bits` (exists). - Tools: `cpl explain` layouts and peak memory, the `wide_array` lint, the build-time memory warning. ## Later - **Vectorization by judge profile.** A profile names the instruction set (`isa: avx2`); codegen emits the matching `#pragma GCC target` and, for loops whose shape it can prove (narrow-width element loops, `Group` and `Selective` folds, prefix scans), vectorizes them itself. `cpl explain` says which loops vectorized and why the others didn't. Not designed yet. ## Open 1. **`wide_array` threshold.** 1e6 cells is a guess; the goal is to flag the arrays that decide MLE and stay quiet otherwise. --- # Round 1: indices and ranges URL: /docs/ref/core/04-indices This is the normative specification ([source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/core/04-indices.md)). For a gentler introduction, start with the [guides](/docs/guides). Everything else in the stdlib indexes by these, so they come first. ## The model in one paragraph A **domain** is a finite, ordered index type. Its members are **positions**. Between and around positions sit **cuts**: a domain of n positions has n + 1 cuts, `D.cuts`. A **range** is a contiguous run of positions, and its two ends are cuts. Arrays are `[D]T`, indexed only by `D`, so a vertex never indexes an edge array and a cut never indexes a position array. ```cp domain V = 1..=n // positions 1..n domain Pos = 0..n // positions 0..n-1; Pos.cuts is cuts 0..=n let (domain C, comp) = compress(xs) // fresh domain from a computation domain Cell = (Row, Col) // product: [Cell]T and [Row, Col]T are one 2-D array type domain State = (comps: 0..=n, used: 0..l) // named factors: s.comps, State.at((c, u)) -> ?State enum Dir = N | E | S | W // a fieldless enum is a domain too: [Dir]Int ``` ## Domains | Form | Meaning | Cost | |---|---|---| | `for v in V`, `V.rev` | positions in order or reverse order | O(1) per step (R04.2.1) | | `V.count` | number of positions | O(1) (R04.2.2) | | `V.first`, `V.last` | `?V`, `None` when `V` is empty; write `V.first!` when you know it isn't | O(1) (R04.2.3) | | `V.range` | the whole range, same as `..` (`a.keys` for an array's) | O(1) (R04.2.4) | | `V.cuts` | the domain of cuts (type `Cut`): `V.cuts.first` is the start, `.last` the end | O(1) (R04.2.5) | | `x in V` | is integer `x` a position | O(1) (R04.2.6) | | `V(x)` | integer to position, trapping outside `V` | O(1) (R04.2.7) | | `V.at(x)` | integer to position, `?V`: `None` outside `V` | O(1) (R04.2.8) | | `P.nth(k)` | a product domain walks row-major (the last factor fastest), so `P.nth(k)` decodes a flat 0-based cell number and `for (r, c) in P` visits rows in order | O(1) (R04.2.9) | | `P.at((x, y))`, `P((x, y))` | for a product domain `P = (A, B)`, a tuple of integers to a position: `None` (or a trap) unless every part lies in its factor, so a neighbour that may fall off is `if let q = P.at((r - 1, c))` | O(1) (R04.2.10) | | `let (r, c) = p`, `p.0` | a position of a product domain is a tuple of factor positions: tuple patterns and `.0`/`.1` work on it, named factors too | O(1) (R04.2.10) | | `v.after`, `v.before` | the pieces `v.r..` and `..v.l` of `v`'s domain, so `for j in v.after` walks the positions after `v` | O(1) (R04.2.19) | | `a[p]`, `a[x, y]` | for `P = (A, B)`, `[P]T` and `[A, B]T` are the same type: a `p: P` indexes it whole, its parts index it one by one, and `[P] p => f(p)` builds it | O(1) (R04.2.11) | | `Pair` | the unordered pairs `{u, v}` of distinct positions, `V.count * (V.count - 1) / 2` of them, walked by `hi` then `lo` (lower-triangle order); `[Pair]T` is packed, and `d[u, v] == d[v, u]` (decision 164) | O(1) (R04.2.12) | | `V.wrap(x)` | integer to position, mod `V.count`: rings and cyclic shifts | O(1) (R04.2.13) | | `if let V(j) = i - 10:` | the pattern form of `V.at`: matches only inside `V` | O(1) (R04.2.14) | | `Int(v)` | position to its integer (for `1..=n`, that's 1..n) | free (R04.2.15) | | `Int(c)` | cut to its integer: the number of positions before it, 0..=n whatever the base (`1..=n`: `v.l` is v-1, `v.r` is v; `0..n`: v, v+1) | free (R04.2.16) | | `V.cuts(k)`, `V.cuts.at(k)` | integer to cut: trapping, or `?V.cuts` | O(1) (R04.2.17) | | `5` where a `V` or `V.cuts` is expected | integer literal is that position or cut (integer domains; also fills `[d]V.cuts = 0`); outside a static bound it is a compile error | free (R04.2.18) | **Pieces.** Coordinate compression for intervals: `let (domain P, piece) = D.pieces(cuts: cs)` splits a range at the given cuts into the pieces between them, with `piece[p]` the `Range` each covers (so `piece[p].len` is its real length) and `piece.covering(a..=b)` the `Range

` that tiles `a..=b`. Inputs are cuts, pieces are ranges, so the `b + 1` and `- 1` of hand-rolled compression never appear (decision 162). ## Positions and cuts move the same way | | neighbour of the same kind | the other kind, either side | |---|---|---| | position `v` | `v.prev`, `v.next`: `?V` | `v.l`, `v.r`: its cuts (R04.3.1) | | cut `c` | `c.prev`, `c.next`: `?V.cuts` | `c.l`, `c.r`: the positions beside it, `?V` (R04.3.2) | `v.next(k)`, `v.prev(k)` step k at once, `?V` (cuts too). `c.shift(r)` is the cuts at distances `r` after cut `c`, clipped to the domain and possibly empty (chords of length `lo..=hi` from `c` end in `c.shift(lo..=hi)`). `D.mask(xs)` is the `[D]Bool` marking the positions a sequence yields. `D.ring.step(x, d)` steps `d` positions with wraparound. `.next` is `.next(k = 1)`: only methods marked `@get` (which promises O(1)) read without parentheses, and an `@get` method may take defaulted parameters. A plain method always needs `()`, so nothing costly hides behind a bare name. One rule: `.l`/`.r` switch kind (left or right side), `.prev`/`.next` keep it. The receiver's kind is static, so a mix-up is a type error. `v.l..v.r` is exactly `v`; a prefix DP reads `dp[v.r] = f(dp[v.l], a[v])`. Arithmetic on a position gives an `Int` (`v + 1`); getting back into the domain is explicit (`v.next`, `V(x)`). (R04.3.3) Arrays over an anonymous range (`[0..=n]Int`) take any `Int`, checked, so ordinary DP tables stay plain. ## Ranges ### Two kinds of range, one type `Range` is a contiguous run of a domain `D`. `V.cuts` is a domain like any other, so there are two kinds you meet in practice, and every method below is generic over `D`: it means the same thing on both. | | `Range`: over positions | `Range`: over cuts | |---|---|---| | written | `l..r`, `l..=r` with position ends | `j..i`, `j..=i` with cut ends (R04.4.1) | | elements (`for`, `in`, `len`) | positions | cuts (R04.4.2) | | typical use | a piece of the array: slice, fold, cost | split points, prefix lengths, answers that may be 0 or n | | example | `a[l..=r]`, `seg.fold(l..r)` | `for j in ..i`, `for k in a..=b` | **The rule: a range's elements are the kind of its ends.** Cuts in, cuts out: `for k in a..=b` walks cuts a through b, `for j in ..i` walks the cuts before i. ### One exception, in how a literal is typed: the piece Cuts `j` and `i` bound a piece of the array: the positions between them. So a half-open range literal with cut ends, written where a `Range` is expected, builds that `Range` directly: ```cp for j in ..i: // ..i: no Range expected, so cuts dp[i] min= dp[j] + cost(j..i) // cost takes Range: j..i is the piece pre.fold(j..i) a[j..i] seg.fold(j..i) // same: these take Range ``` This is **not a conversion and there is no implicit `Into`.** It decides what the literal builds, exactly like `5` becoming a position where a `V` is expected. Consequences: - Only the literal `a..b` does it. A stored cut range never becomes a piece: `let s = j..i; cost(s)` is a type error whose fix is to write `cost(j..i)`. (R04.4.5) - Only half-open: `j..=i` on cuts names no piece, so it's an error where a `Range` is expected. (R04.4.6) - It's safe because the two readings are the same set: cut `c` in `j..i` stands for the position `c.r`, and the cuts j..i-1 are exactly the left edges of the positions between `j` and `i`. ### Open-ended ranges Leaving out an end means the edge of the other end's domain, so the domain never has to be named and never has to be non-empty: | written | means | elements | |---|---|---| | `..i` | `D.first..i`, where `i: D` | everything before `i` (R04.4.8) | | `..=i` | `D.first..=i` | everything up to and including `i` (R04.4.9) | | `i..` | `i..=D.last` | `i` and everything after it (R04.4.10) | | `..` | all of the indexed dimension | only inside `[...]`: `grid[r, ..]` (R04.4.11) | A literal end is a **position** of the indexed domain unless the other end is a cut (then it is a cut, as in the piece rule above). On `domain V = 1..=n`, `a[..5]` is positions 1..=4 and `a[..=5]` is 1..=5; `a[..V.cuts(5)]` writes the cut. Integer literals never mean a count of positions. They follow the ends rule like any range: `for j in ..i` with a cut walks cuts, and `for j in v.r..` walks cuts too. A half-open open-ended literal with a cut end is a piece where a `Range` is expected, so `a[..c]` and `a[c..]` slice. For the positions after `v`, write `for j in v.next..` only when `v.next` exists, or `for j in a[v.r..].keys`; see Open. `..i` needs no `!`: `i` existing proves its domain is non-empty. Cost: O(1) to build, like any range. ```cp for j in ..i: // every cut before i dp[i] min= dp[j] + cost(j..i) let best = a[..c].max() // the prefix left of cut c ``` The language's implicit conversions are this closed list, none user-extensible. Each applies wherever an expected type is known: a binding or field with a declared type, an argument, a return value, an assignment, and either operand of `==`, `!=` or a comparison whose other operand fixes the type. Nothing else converts. (R04.4.22) 1. **`T` to `?T`.** `u != from` with `from: ?V` compares `Some(u)` with `from`. Free. (R04.4.23) 2. **A range type to a wider one** (`1..=5` to `Int`, `0..=9` to `-5..=100`). Free. Arithmetic on range types yields `Int` (chapter 3), so a sum of weights `1..=1e9` is an `Int`, and a path distance or `dist: [V]?W` built from one is `Int` unless declared narrower. (R04.4.24) 3. **Integer literal to position or cut** of an integer domain (R04.2.18). For a domain with a runtime count (`domain V = 1..=n`, `n: 1..=2e5`), a literal outside the domain at its largest count is a compile error; one inside the domain at its smallest count is proven; one between is checked like any unproven position. (R04.4.25) 4. **Cut range to piece:** a literal `j..i` whose ends are cuts, where a `Range` is expected, is the piece between them (see R04.4.21). (R04.4.26) 5. **Scalar to array fill:** a value `x: T` where `[D]T` is expected is the array over `D` with every element `x`, evaluated once: `var dist: [V]?Int = None`, `var dp: [0..=n]Int = 0`. Same as `[D].filled(x)`; `[D]` followed by a value without `=>` is a type, never a table. (R04.4.27) **Integer ranges as domains.** An integer range `lo..hi` (or `lo..=hi`, or a counted `[n]`, which is `0..n`) used as an answer space or array dimension is an anonymous domain: it satisfies `Domain`, its positions are the `Int`s in it, and the cut before position `x` is the `Int` `x`, so its cuts run `lo..=hi` for `lo..hi`. `(1..=5).bsearch(x => x >= 3)` is `3`, the first position where `ok` holds, and `Graph.directed` accepts the counted edges of `read<[m](u: V, v: V)>()`. R04.2.16 (`Int(c)` counts the positions before `c`) is for declared domains, where the two agree when the base is 0. (R04.4.28) A general implicit `Into` is the C++ trap: conversions that don't show and overloads that turn ambiguous. ### Methods All of these are on every `Range`. The two right columns spell out what the generic meaning comes to for each kind. | Form | On `Range` (positions) | On `Range` (cuts) | Cost | |---|---|---|---| | `r.len`, `r.is_empty`, `x in r` | count of positions; membership of a position | count of cuts; membership of a cut | O(1) (R04.4.12) | | `for x in r`, `r.rev`, `r.step(k)` | positions | cuts | O(1) per step (R04.4.13) | | `r.first`, `r.last` | end positions, `?V` | end cuts, `?V.cuts` | O(1) (R04.4.14) | | `r.l`, `r.r` | the bounding cuts, `V.cuts` | the bounds one level up (`V.cuts.cuts`); you rarely want them: use `r.first`/`r.last` | O(1) (R04.4.15) | | `r.clip(s)` | intersection | intersection | O(1) (R04.4.16) | | `r.halve()` | `?(r.l..r.mid, r.mid..r.r)`, two non-empty halves; `None` when `len <= 1` | same, over cuts | O(1) (R04.4.17) | | `r.mid` | middle cut, `V.cuts`, always present (`r.l` when empty) | the middle gap, one level up | O(1) (R04.4.18) | | `r.first_true(ok)`, `r.last_true(ok)` | first position where false→true `ok` holds; last where true→false `ok` holds; `?V` | same over cuts, `?V.cuts` | O(log n) calls (R04.4.19) | | `r.bsearch(ok)`, `r.bsearch(ok, last: true)` | the cut where `ok` flips (false→true; with `last:`, true→false), `V.cuts`; always exists | the gap between cuts, one level up; use `first_true` | O(log n) calls (R04.4.20) | | `a[r]`, `pre.fold(r)`, `seg.fold(r)` | the piece `r` | n/a: takes `Range`; a literal `j..i` is the piece | as the API says (R04.4.21) | **Binary search: which element, or where it flips.** `first_true` and `last_true` return the element, so the predicate reads like the statement and is never negated; `None` when no element qualifies (an empty range is the case with no elements). `bsearch` returns the cut where `ok` turns true, which always exists, for answers that are boundaries: insertion points, counts, prefix lengths. They agree: `r.first_true(ok)` is `r.bsearch(ok).r` and `r.last_true(ok)` is `r.bsearch(ok, last: true).l`. ```cp let k = (0..=n).last_true(k => cost(k) <= budget) ?? -1 // largest k that fits let k = (0..=n).first_true(k => cost(k) >= x)! // smallest k that reaches x let c = V.cuts.range.last_true(c => pre[c] <= s)! // longest prefix with sum <= s: a cut let below = Int(a.keys.bsearch(i => a[i] >= t)) // how many of sorted a are < t ``` `ok` must be monotone in the direction the name says: false→true for `first_true` and `bsearch`, true→false for `last_true` and `bsearch(ok, last: true)`. Checked builds check that the probes already made agree with one boundary (every true probe after every false one, O(1) per probe), which catches most non-monotone predicates; they never call `ok` more often than release does (see R09.2.3). Answer spaces that aren't a domain are integer ranges, an anonymous domain whose positions and cuts are both `Int`: `(0..=1e18).first_true(t => fits(t))`. ```cp fn inversions(r: Range) -> Int: // merge-sort shape let (left, right) = r.halve() else: return 0 inversions(left) + inversions(right) + cross(left, right) fn solve(rows: Range, opts: Range): // D&C DP optimisation if rows.is_empty: return let m = rows.mid.r! let best = opts.clip(..m.r).min_by(k => cost(k, m))! dp[m] = cost(best, m) solve(rows.l..m.l, opts.l..best.r) solve(m.r..rows.r, best.l..opts.r) ``` These replace `bsearch_first` and `bsearch_last`. Rejected: only the flip cut, with `.l`/`.r` picking the side (last-true needs a negated predicate, a `>` vs `>=` bug source); `bsearch(ok, last: true)` returning an element (a flag where a name says it better; the flag stays on `bsearch`, where it only says which way `ok` runs); detecting the direction (ambiguous when `ok` is constant); a sentinel end when nothing qualifies (looks like a real answer). ## Arrays over domains ```cp var dist: [V]?Int = None // fill let deg = [V] v => g.deg(v) // build from a fn let a: [Pos]Int = read() // read n values pre[i] - pre[j] pre.fold(j..i) // prefix sums are indexed by cuts a[l..=r] // a slice view, O(1), lent a.keys a.items a.map(f) // V, (V, T), [V]U grid[r] // a row view of [Row, Col]T ``` ## Empty domains Domains may be empty: iteration, arrays and folds over an empty domain just work. `V.first`/`V.last` are `?V`, so the empty case is visible where you ask for an end: ```cp let m = read<0..=2e5>() domain E = 0..m let e = E.first! // traps naming `E` when m == 0 let e = E.first ?? return // or handle it ``` No `NonEmpty` bound: the checker does not track emptiness. Tried and dropped for now (decision 137); `!` is one character and says the same thing. ## Middle of a range `r.mid` is the middle cut: ⌊n/2⌋ elements before it (C++'s `(l + r) / 2` on a half-open range), always present. `r.halve()` is `(r.l..r.mid, r.mid..r.r)`, `None` when either half would be empty. | n | `r.halve()` | `r.mid` | `r.mid.r` | |---|---|---|---| | 0 | `None` | `r.l` | outside `r` (guard first) (R04.7.1) | | 1 | `None` | `r.l` | the element (R04.7.2) | | ≥ 2 | ⌊n/2⌋ and ⌈n/2⌉ elements | `left.r` | `right.first` (R04.7.3) | `halve` is for the merge-sort shape (stop at one element). The element shape (handle the middle, recurse around it, stop at empty) is `if r.is_empty: return` then `r.mid.r!`; lint flags `.mid.r` with no emptiness guard. Rejected: `r.mid: ?V`, the middle element (safe on empty, but the cut is what both shapes share, and `halve` reads as its definition). ## Decided (decision 137) - `.l`/`.r` switch kind, `.prev`/`.next` keep it; `.next(k)`/`.prev(k)` step k. (R04.8.1) - Position arithmetic gives an `Int`; back into the domain is explicit. (R04.8.2) - `r.first_true(ok)`/`r.last_true(ok)` return `?` the element; `r.bsearch(ok)` returns the flip cut, always present; `last: true` for true→false. They replace `bsearch_first`/`bsearch_last`. (R04.8.3) - Empty domains are valid; `V.first`/`V.last` are `?V` (no `NonEmpty` bound). (R04.8.4) - One generic `Range`; elements are the kind of the ends, so `a..=b` on cuts is cuts. The half-open literal `j..i` with cut ends builds the piece where a `Range` is expected (124): literal typing, not a conversion; no implicit `Into`. A position-only reading was rejected: it broke `for j in ..i: dp[j] + cost(j..i)`. (R04.8.5) - `..i`, `..=i`, `i..` are open-ended ranges over the end's domain; bare `..` only inside `[...]`. (R04.8.6) - `r.mid` is the middle cut, always present; `r.halve()` is `?(r.l..r.mid, r.mid..r.r)`, `None` at length <= 1. (R04.8.7) - Integer literals convert to positions and cuts of integer domains. (R04.8.8) - `V(x)` traps outside `V`; `V.at(x)` is `?V`; the pattern `V(j)` refutes. (R04.8.9) - A list literal for `[D]T` gives one value per cell, so `[]` fills an empty `D`; a list whose length differs from a written count is a compile error, and from a run-time count a trap. (R04.8.10) Rejected: `.start`/`.end`/`.before`/`.after` (four words for one idea); `.n`/`.p` (`n` reads as a count, `p` as parent); `V.first` always trapping (hides the n = 1 case until a hidden test hits it); `@get`-free bare calls (silent cost); `V.try(x)` (`try` reads like error handling). `r.split(at: c)` (`r.l..c` and `c..r.r` say it directly, and also say "all but `v`": `r.l..v.l`, `v.r..r.r`). ## Open None. (The positions after `v` are `v.after`, decision 186.) --- # Index identity vs offset URL: /docs/ref/core/04a-identity-vs-offset This is the normative specification ([source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/core/04a-identity-vs-offset.md)). For a gentler introduction, start with the [guides](/docs/guides). What does `w[i]` mean when `w` is a slice, and what index does a search inside a slice return? This doc lists the cases contest code actually hits, scores each option on every case, and picks the option that does best. Examples cite the gold solutions and dreams where possible. ## The options | | Domain slice `a[l..=r]` of `[V]T` | `List`/`Str` slice `s[l..r]` | |---|---|---| | **I. Identity everywhere** | keeps `V`'s positions | keeps the source's `Int` keys `l..r` | | **O. Offset everywhere** | renumbered `0..len`, keyed by `Int` | renumbered `0..len` | | **H. Hybrid** (current round 2 text) | keeps `V`'s positions | renumbered `0..len` | Scores in the tables: - ✓ works as written - \+ needs extra code that is easy to forget (an `+ l` or `- l`) - T wrong code traps, at compile time or on the first wrong access - S wrong code reads the wrong element and keeps going S is the score that matters. The design rules rank a compile error over a trap, and a trap over silent wrongness. ## A. Order-only uses: no key is ever observed Most slice uses never look at a key, so the choice doesn't affect them. | Case | Example | I | O | H | |---|---|---|---|---| | A1 walk, fold, print | `print(perm[lo..hi])`, `w.sum()` | ✓ | ✓ | ✓ (R04a.2.1) | | A2 compare two slices | `tuples[i - 1][..cl] != t[..cl]`, `b[j..].starts_with(a[span[s]])` | ✓ | ✓ | ✓ (R04a.2.2) | | A3 concatenate, collect | `p[..2 * skip].even + p[2 * skip..]` | ✓ | ✓ | ✓ (R04a.2.3) | | A4 zip slices at different offsets | `zip(ord[n - m..].rev, ord[k..n - m].rev)` | ✓ | ✓ | ✓ (R04a.2.4) | | A5 assign into a range | `q[start..] = suffix`, `dp[mid..hi] += dp[mid..hi.prev]` | ✓ | ✓ | ✓ (R04a.2.5) | | A6 in-place verbs | `a[l..=r].sort()`, `.reverse()` | ✓ | ✓ | ✓ (R04a.2.6) | | A7 consume from the front | `rest.first`, `rest = rest.drop(1)` | ✓ | ✓ | ✓ (R04a.2.7) | | A8 copy out | `List(w)`, `Str(s[l..r])` | ✓ | ✓ | ✓ (R04a.2.8) | | A9 length-only results | `period(t[start..start + delta])` | ✓ | ✓ | ✓ (R04a.2.9) | This group only works under every option because of one rule: **any operation that combines two sequences pairs them by walk order, never by key.** That covers `==`, `<`, `starts_with`, `zip`, `+`, slice assignment and elementwise `+=`. The rule holds regardless of which option wins, and round 2 should state it. ## B. An index found inside the slice, used outside it | Case | Example | I | O | H (domain) | H (List/Str) | |---|---|---|---|---|---| | B1 arg-extreme in a range | D&C: `let m = a[l..=r].argmax()`, then `b[m]`, recurse on `l..m` | ✓ | + / S | ✓ | + / S (R04a.3.1) | | B2 search in a range | `a[l..r].bsearch(x)`, `s[l..].search(c)` | ✓ | + / S | ✓ | + / S (R04a.3.2) | | B3 update parallel arrays | `for (i, x) in a[l..=r].items: dp[i] = …` | ✓ | + / S | ✓ | + / S (R04a.3.3) | | B4 prefix of a range | `a[l..=r].scan(+)[c]` with a source cut `c` | ✓ | + / S | ✓ | + / S (R04a.3.4) | C++ itself answers B with identity: `max_element(a + l, a + r) - a` and `lower_bound(a + l, a + r, x) - a` give absolute positions. Python's `s.find(c, l)` is absolute too. Only Python's `s[l:].find(c)` is relative, and adding `+ l` to it is a well-known Python bug. ## C. An outside index used on the slice | Case | Example | I | O | H (domain) | H (List/Str) | |---|---|---|---|---|---| | C1 source position into a view | `blk[i]` inside a D&C on `blk = a[i.l..end]` | ✓ | + / S | ✓ | + / S (R04a.4.1) | | C2 nested slicing | `w[a..b]` with `a`, `b` from the source | ✓ | + / S | ✓ | + / S (R04a.4.2) | | C3 a range cut into halves | `let (x, y) = r.halve()`, then `a[x]`, `a[y]` | ✓ | + / S | ✓ | + / S (R04a.4.3) | ## D. Counters and literals into the slice | Case | Example | I | O | H (domain) | H (List/Str) | |---|---|---|---|---|---| | D1 literal first or last | `w[0]`, `w[w.len - 1]` | T | ✓ | T (compile) | ✓ (R04a.5.1) | | D2 counter loop | `for i in 0..w.len: w[i]` (festival's `rest[i]`) | T | ✓ | T (compile) | ✓ (R04a.5.2) | | D3 relative access by variable | `s[l..][k]`, meaning the k-th char after `l` | S | ✓ | T (compile) | ✓ (R04a.5.3) | Why identity scores T on D1 and D2 rather than S: the wrong counter starts at 0. If the slice starts at 0, identity and offset agree, so the code is correct. If it starts later, the first access `w[0]` is outside `w.keys` and traps. Only D3, a variable offset into a slice that happens to land inside the slice's keys, is silent. In practice D3 is written `s[l + k]`. ## E. Generic algorithms run on a sub-sequence | Case | Example | I | O | H (domain) | H (List/Str) | |---|---|---|---|---|---| | E1 a fn written with `xs[0]` / `0..xs.len` gets a slice | user `fn f(xs: List)` | T | ✓ | T (compile) | ✓ (R04a.6.1) | | E2 a per-element table from an algorithm on a slice | `let z = z_function(s[l..])`, then `z[i]` for `i` in `s[l..].keys` | ✓ if keyed like the input; S if 0-based | ✓ | ✓ if keyed like the input | ✓ (R04a.6.2) | E2 is identity's real hazard. It goes away if every per-element result **is keyed like its input** (`z_function(s: S) -> [S.keys]Int`). Arrays over an `Int` range already exist (festival writes `[0..=rest.len]`), so this is a stdlib convention, not a new feature. ## F. Grids and multi-dimensional arrays | Case | Example | I | O | H | |---|---|---|---|---| | F1 row or column view | `grid[r]`, `grid[r, ..]`, `b[.., bv]` | ✓ (keeps the other domain) | S (row loses `C`) | ✓ (R04a.7.1) | | F2 sub-rectangle fold | `inside[..n, ..m].sum()` | ✓ | ✓ | ✓ (R04a.7.2) | ## G. Revision: changing your mind | Case | Change | I | O | H | |---|---|---|---|---| | G1 array ↔ list | `[V]Int` becomes `List` | same meaning | same meaning | slices change meaning; mostly caught, because `V` indices become type errors (R04a.8.1) | | G2 add `.rev` | `a[l..r]` becomes `a[l..r].rev` | `w[i]` is the same element | `w[0]` is now the last element | domain same; List/Str flip (R04a.8.2) | | G3 widen or narrow a slice | `s[l..r]` becomes `s[l - 1..r]` | every index still valid | every offset shifts by one | domain same; List/Str shift (R04a.8.3) | ## H. Keys of the other views | View | I | O / H (List/Str) | |---|---|---| | `.drop(k)`, `.take(k)` | source keys | renumbered (R04a.9.1) | | `.rev` | source keys, walked backwards | renumbered from the far end (R04a.9.2) | | `.even`, `.step(k)` | source keys, strided | renumbered `0, 1, 2…` (R04a.9.3) | | `.map(f)` | source keys | renumbered (R04a.9.4) | | `.filter(p)`, generators | no keys (`Seq`) | no keys (R04a.9.5) | | `.keyed().items` | `(counter, x)`, counter from 0 | `(counter, x)` (R04a.9.6) | | `.items` | `(key, x)` | `(offset, x)` (R04a.9.7) | ## Tally | Group | I | O | H | |---|---|---|---| | A order-only (most uses) | ✓ | ✓ | ✓ | | B index out, C index in | ✓ | silent | ✓ domain, silent List/Str | | D counters and literals | traps, except rare D3 | ✓ | ✓ | | E generic algorithms | traps, ✓ with keyed results | ✓ | ✓ | | F grids | ✓ | breaks | ✓ | | G revision | stable | unstable | unstable for List/Str | - **O** is silently wrong on B, C and F, which are core CP shapes. Out. - **H** is safe on domain arrays but silent on B and C for `List`/`Str`. It also makes the same expression mean different things depending on the source's key type, which shows up in G. - **I** fails loudly almost everywhere it fails. Its one silent case, D3, is rare and has an obvious spelling (`s[l + k]`). Its cost is unfamiliarity: `s[2..5][0]` traps, where Python returns `s[2]`. ## Recommendation: identity everywhere (I) This reverses the hybrid that round 2 currently states. The principle: **an index names the same element everywhere it is valid.** A slice narrows which indices are valid; it never renames them. That holds for domain positions and for `Int` keys alike, so there is one rule. What comes with it: 1. **Order-based pairing** for every operation that combines two sequences (group A). (R04a.11.1) 2. **`.items` gives keys; `.keyed().items` gives a 0-based counter.** Use `.items` when the index goes back into a sequence. (R04a.11.2) 3. **`w.rebase`**: an O(1) view of `w` keyed `0..w.len`, for the rare relative case (D3, or E1 with a fn written 0-based). It allocates nothing. (R04a.11.3) 4. **Per-element results are keyed like their input** (`[S.keys]T`), so `z_function(s[l..])[i]` works with `i` from `s[l..]`. (R04a.11.4) 5. **Diagnostics:** a literal index into a slice is a lint ("`w` starts at `l`; use `w.first` or `w.rebase[0]`"). An out-of-keys access traps naming the slice's key range. (R04a.11.5) 6. **Copies count from 0:** `List(w)`, `Str(w)` and `.collect()` build fresh sequences, keyed from 0. (R04a.11.6) ## Open None. `w.rebase` exists (decision 186), printing and hashing are order-only (A1, A2), and `.enumerate()` is gone (decision 142). --- # Keys: identity everywhere, keys in, keys out URL: /docs/ref/core/04b-keys This is the normative specification ([source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/core/04b-keys.md)). For a gentler introduction, start with the [guides](/docs/guides). Follows `04a-identity-vs-offset.md`, which scored the cases and picked identity everywhere. This doc shows how that choice looks in contest code, in user helpers and in library code. ## The rules 1. **An index names the same element everywhere it is valid.** A slice narrows which keys are valid and never renames them. This holds for every source: domain arrays, `List` and `Str`. `s[2..5][3]` is `s[3]`, and `s[2..5][0]` traps. (R04b.1.1) 2. **Keys in, keys out.** A function given an indexed sequence answers in that sequence's keys: - a position it finds is one of the input's keys (`?K`), valid on the source; - a per-element table is keyed like the input (`[s.keys]T`); - a prefix table is indexed by the input's cuts. (R04b.1.2) Lengths, counts and periods stay `Int`. 3. **Combining two sequences pairs them by walk order, never by key.** This covers `==`, `<`, `starts_with`, `+`, slice assignment and `zip`. `zip(a, b)` is keyed by `a`'s keys. Zipping two different domain types (`[V]T` with `[E]T`) stays a type error. (R04b.1.3) 4. **Ends and relative reads are named.** - `w.first` and `w.last` are the first and last elements (`?T`). - `w.nth(k)` is the element `k` steps from the start. It is 0-based, O(1), and traps past the end. - `w.keys.nth(k)` is the k-th key, because a range is an indexed sequence too. (R04b.1.4) 5. **An array can cover any run of keys.** `[r]T` for a range `r` of `K` is indexed by `K` and valid on `r`, so `[s.keys].filled(0)` is a table shaped like `s`. A declared domain's array covers the whole domain, as before. `[0..=n]Int` is the case we already have, where `K` is `Int`. (R04b.1.5) 6. **Materializing counts from 0.** - `.collect()`, `.sorted()`, `List(w)` and `Str(w)` build a new sequence keyed from 0 (decision 186), like any new order. - To keep `w`'s keys, build a table over them: `[w.keys] k => w[k]`. (R04b.1.6) 7. **A sequence can get a domain of its own.** - `w.rebase` is an O(1) getter returning a `Rebased` view keyed by a fresh domain `0..w.len` that belongs to `w` alone (the `[domain]T` package of 2.14). Binding it with `let t = w.rebase` names the domain `t.Idx`. - `t.Idx` has every domain power: `Int(i)`, `t.Idx(k)`, `t.Idx.wrap(x)`, `[t.Idx]U` tables. Its keys can't be mixed with the source's or with another rebase's. - `a.rekey(r)` is the inverse: the same cells re-keyed onto a range `r` of equal length, O(1), trapping on a length mismatch. Library code uses it to hand results back in the caller's keys. (R04b.1.7) Diagnostics: - **Lint: literal index into a slice** (`w[0]`, `w[1]`). Suggests `w.first` or `w.nth(1)`. (R04b.1.8) - **Lint: 0-based counter used as a slice key** (`for k in 0..w.len: w[k]`). Suggests `w.items`, `w.nth(k)` or `w.rebase`. (R04b.1.9) - **Trap: an out-of-keys read.** The message names the key range, e.g. "`w` has keys 3..7 (it is `s[3..7]`); use `w.nth(0)` for its first element". (R04b.1.10) - **Compile error: a raw `Int` used to index a domain slice**, as before. (R04b.1.11) ## Contest code **Divide and conquer on the maximum (B1).** The position found inside the slice is a position of `a`, so it indexes `b` and splits the range directly. ```cp fn solve(r: Range) -> Int: if r.len == 0: return 0 let m = a[r].argmax()! // m: V, valid on a and b solve(r.l..m.l) + solve(m.r..r.r) + b[m] * r.len ``` **Search in a suffix (B2).** `search` answers in `s`'s keys, so the token is `s[l..j]` with no `+ l`. ```cp var l = 0 while l < s.len: let j = s[l..].search(',') ?? s.len // a key of s words.push(s[l..j]) l = j + 1 ``` **A per-element result on a piece (E2).** The table is keyed like the piece, so `i` from `s[l..]` reads it directly. ```cp let z = z_function(s[l..]) // [l..s.len]Int let hits = s[l..].keys.count(i => z[i] >= k) // suffixes starting with s[l..l + k] ``` **Parallel arrays over a range (B3).** ```cp for (i, x) in a[l..=r].items: // i runs over l..=r best[i] = x * w[i] ``` **Consuming from the front (A7).** The keys of `rest` shrink, and the elements never move. ```cp var rest = a[..] while let x = rest.first: if x > budget: break budget -= x rest = rest.drop(1) ``` **Comparing pieces (A2, rule 3).** Pairing is by walk order, so the offsets don't matter. ```cp if s[i..i + k] == s[j..j + k]: ... let lcp = zip(s[i..], s[j..]).take_while((x, y) => x == y).count() ``` **Relative reads.** ```cp s[l..].nth(k) // the k-th character from l; same as s[l + k] w.first!, w.last! // the ends of a non-empty piece ``` **Grids (F1).** A row keeps the column domain and a column keeps the row domain. ```cp for (c, x) in grid[r].items: ... // c: Col let col = grid[.., c] // [Row]T view ``` **A 0-based algorithm on a piece (rule 7).** `rebase` gives a domain for the piece, and the domain's own tools (`wrap`) do the arithmetic. ```cp let t = s[l..r].rebase // t: [t.Idx]Char, keys 0..r - l let rotated = Str(t[t.Idx.wrap(Int(i) + k)] for i in t.keys) ``` ## User helpers **Preferred: generic over keys.** A parameter typed `[K]T` is a view type: it accepts an array, a `List`, a `Str` or any slice of them (any `Indexed`; with `mut`, any `IndexedMut`), and the helper answers in the caller's keys. It walks `a.keys`, never all of `K`: on a slice, `a[k]` outside `a.keys` traps in checked builds. Only an owned `[D]T` promises every key of `D`. This is the same code as stdlib code, with no extra power. ```cp fn first_drop(a: [K]Int) -> ?K = a.keys.drop(1).find(i => a[i] < a[i.prev!]) fn next_greater(a: [K]Int) -> [K]?K = // keyed like a var res = [a.keys].filled(None) var stack = List() for i in a.keys: while let j = stack.last and a[j] < a[i]: res[j] = i stack.pop() stack.push(i) res ``` Both work unchanged on `a`, on `a[l..=r]` and on `a.rev`. Their results index the source. **A helper that takes a container.** `List` and `Str` parameters accept only that container, because the callee may grow it (`push`, `pop`, `clear` need the concrete type). `fn f(xs: List)` called with `s[3..7]` is a type error with two fixes: - make `f` generic as above, using `first`, `nth` and `items`; (R04b.3.1) - call `f(List(w))`, an O(len) copy keyed from 0. (R04b.3.2) ## Library code Stubs keep `= todo` bodies. The bodies here show that "keys in, keys out" costs a library author nothing. **Position queries return keys.** ```cp /// O(n). A key of the largest element, the first on ties; `None` when empty. pub fn argmax(self: [K]T) -> ?K = self.keys.max(by: k => self[k]) /// O(n·|p|). The first key where `p` starts, valid on the source of a slice. pub fn search, K, P>(self: S, p: P) -> ?K = todo ``` **Per-element tables are keyed like the input.** The algorithm runs on offsets through `nth`, and `rekey` hands the table back in the caller's keys. ```cp /// O(n). `z[i]` is the longest common prefix of `s[i..]` and `s`, keyed by `s.keys`. pub fn z_function(s: [K]T) -> [K]Int = let n = s.len var z = [0..n]0 var (l, r) = (0, 0) for i in 1..n: if i < r: z[i] = min(r - i, z[i - l]) while i + z[i] < n and s.nth(z[i]) == s.nth(i + z[i]): z[i] += 1 if i + z[i] > r: (l, r) = (i, i + z[i]) z.rekey(s.keys) ``` **Prefix tables use the input's cuts,** so `a[l..r].scan(+)[c]` takes a cut `c` of `a`: ```cp pub fn scan(self: [K]T, f: (T, T) -> T, from: ?T = None) -> Prefix = todo ``` **Getting a domain from what you were given (rule 7).** | Need | Write | Gives | |---|---|---| | Work in the caller's keys | take `[K]T` | `K` itself; nothing to build (R04b.4.1) | | A table over exactly `s`'s keys | `[s.keys]x` | `[K]T` valid on `s.keys` (R04b.4.2) | | A private 0-based index space for `s` | `let t = s.rebase` | view over fresh `t.Idx` (R04b.4.3) | | An owned list as a domain array | `let (domain I, b) = xs.with_domain()` | `[I]T` that owns its cells (R04b.4.4) | | Results back in the caller's keys | `table.rekey(s.keys)` | O(1) re-key (R04b.4.5) | ## Spec changes this implies | Stub | Today | Becomes | |---|---|---| | `search`, `rsearch` | `-> ?Int` on `Str` | `-> ?K` on any `Indexed` (R04b.5.1) | | `find_all`, `shift_and`, `KmpAutomaton.find_all` | `yields Int` | `yields K` (R04b.5.2) | | `z_function`, `prefix_function`, `prefix_matches` | `-> List` | `-> [K]Int`, keyed by `s.keys` (R04b.5.3) | | `min_rotation`, `max_rotation` | `-> Int` | `-> ?K`, the start, `None` when empty (R04b.5.4) | | `lyndon_factorization` | `-> List` | `-> List`, the starts (R04b.5.5) | | `Palindromes.longest_at(i)` | `i: Int` | `i: K` (R04b.5.6) | | `period`, `borders`, `common_prefix_len`, `overlap` | `Int` lengths | unchanged (R04b.5.7) | | `seq.cp` | `nth_element` | renamed `select(k)`, so `nth` means one thing (R04b.5.8) | | `seq.cp` | none | `nth`, `rebase`, `rekey` added (R04b.5.9) | | sequences doc §"Slices" | the hybrid | rule 1; the pending note goes | ## Open 1. **Is `rekey` worth a name?** The alternative is writing into `[s.keys]` through `s.keys.nth(i)`. That's correct, but it puts a key lookup in every hot-loop write. 2. **Should a `List` parameter renumber automatically?** I say no: the parameter is lent the caller's slice with its keys, and that's what makes B and C safe. A helper that wants 0-based takes `List(w)`. --- # Ownership, mutation and lending URL: /docs/ref/core/05-ownership This is the normative specification ([source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/core/05-ownership.md)). For a gentler introduction, start with the [guides](/docs/guides). This page is the whole model. After reading it you should be able to look at any snippet and say whether it compiles, and which rule decides it. It supersedes the shorter statements in `core/12-powers.md` W4/W8, `plan/14-state.md` and `plan/19-index-and-lends.md` §3.4 to §5 where they differ; §13 lists every difference and why. There are no lifetimes, no reference types and no pointers. Every value is **owned** or **lent**, the checker infers which, and twelve rules (R1 to R12) say what each may do. ## 1. The model in six sentences 1. A variable owns its value; `let` can't change it, `var` can. 2. Small values with no heap part copy; heap values (`List`, `Map`, `Str`, `[D]T`, structs holding them) move, and copying one is `.clone()`. 3. A parameter is a lend of the caller's value: the callee can use it but never keep it, and `mut` (written at both ends) lets it change it. 4. A value built from a lend is itself lent: slices, views, generator values, loop items, projection results, closures over local state. 5. While a lent value is alive (until its last use) its sources are frozen for writes, or untouchable if it is a `mut` lend; and it can never be kept anywhere that outlives them. 6. Each call is checked as one access to everything it touches: its arguments and whatever the called fn or closure captures. ### Six models 1. **Values, not objects.** No two variables refer to the same list: `let b = a` moves or copies, never aliases. Mutation is always to a name you can see. 2. **A lend is "I'm looking at it, so it holds still".** Read: many lookers, no writers. `mut`: one looker, who may write. 3. **Looking lasts until your last glance,** and never past the block it started in. 4. **A call looks at everything it touches** for its duration: arguments and whatever its fn and closure arguments capture. 5. **Fns and closures are code, not views.** They look only while running. 6. **"Holds still" means the answers, not the bytes.** A `@cache` field (§10a) may change how answers are stored, never what they are. The danger the rules prevent is a reader whose view a write breaks or changes underneath it (iterator invalidation, a slice summed while it changes, two names for one element). So the question is always: does anyone hold a live view this write would break? ### Proved, promised, unsafe | Tier | Spellings | If broken | Surfaced by | |---|---|---|---| | Proved | moves, lends, R1 to R12 | can't be | the compiler | | Trap | `!`, indexing, `assert`, preconditions such as sortedness | stops with a message | debug builds check every one | | Promise | `@cache`, `@law` | wrong answers, never undefined behaviour | `cpl explain` lists each; stress runs check them | | Unsafe | `@trusted:` blocks, `@cpp("...")` bodies | anything | `cpl explain` lists each; debug shadow checks where possible | Anything the compiler trusts without proof is an `@` attribute from this closed list, so `grep -E '@(cache|law|trusted|cpp)'` finds all of it, and adding to the list takes a decision entry. Codegen never optimizes on a promise (no `__restrict` from a `disjoint` law), which is what keeps a broken promise from becoming undefined behaviour. ### The picture Every live lent value points at the variables it borrows. A variable with a pointer at it is frozen: no writes under a read lend, no access at all under a `mut` lend. The pointer goes away at the value's last use, and it may never outlive the variable (R8). That is the whole checker. - **Values built from arguments hold pointers:** slices, views, projection results, structs with a lent field, generator values. They lend from when they are made to their last use. - **Fns and closures hold no lends.** A call acts as if everything they capture were passed as extra arguments at that moment. They only hold the captured variable's name: it can't move while they live, and they can't outlive it. ```cp let walk = dfs(g, s, mut seen) // seen lent `mut` from here... print(seen[x]) // error: seen is lent to walk let n = walk.count() // ...to here fn walk2() -> yields V: ... // same DFS, using seen as a capture print(seen[x]) // fine: walk2 touches seen only while it runs let n2 = walk2().count() ``` ## 2. Plain and heap values (R1, R2) **R1. Plain values copy.** A value is plain when no part of it lives on the heap: `Int`, `Bool`, `Char`, `F64`, `Mod

`, positions, cuts, ranges, optionals, tuples, records and enums of plain values, fn values that capture only plain values. Using a plain value never affects the original. (R05.2.1) **R2. Heap values move.** `List`, `Map`, `Set`, `Str`, `[D]T`, `Graph`, `SegTree` and any struct, tuple or enum holding one move when bound, passed to a constructor, put in a container or returned. Using a variable after it moved on any path to that use is a compile error, including a move in one branch of an `if` or in an earlier iteration of a loop; `x.clone()` is the explicit O(n) copy. A move is O(1) (a few words), never a deep copy. (R05.2.2) ```cp var xs = List(1, 2) let ys = xs // xs moves into ys print(xs.len) // error: xs moved on the line above; write xs.clone() there ``` ```cp let k = 5 let j = k // plain: a copy print(k + j) // fine ``` `let b = a` where `a` is used again is the error above, never a silent copy (decision 128). Moving out of a place that stays alive, such as an element, is `xs[i].take()`, which exists only where the type has an empty value to leave behind: `None` in a `?T`, the empty `List`, `Str`, map or set. For anything else, `xs[i].replace(x)` returns the old value. ## 3. Bindings and places - `let x = e` binds `x` to `e`; `x` can't be reassigned or mutated. (R05.3.1) - `var x = e` binds a mutable variable: `x = e2`, `x.push(..)`, `x[i] = ..`. (R05.3.2) - A **place** is a variable, a field (`s.f`), an element (`a[i]`), a slice (`a[r]`) or any projection result (§6). Places are what `mut` lends. (R05.3.3) - `let p = mut a[i]` names a place: `p += 1` writes `a[i]`. `p` is a `mut` lend of `a` (R7). (R05.3.4) - Reading an element or field binds a lend of it, not a copy, when the value is heap (`let row = rows[i]`: §6, `at` is a projection). A plain element copies (`let x = a[i]`). (R05.3.5) **R3. Mutation needs a mutable place.** Writing, pushing, calling a `mut self` method, or passing `mut x` requires `x` to be a `var`, a `mut` parameter, or a `mut` lend (`let p = mut ...`). `let` bindings and plain parameters are read-only all the way down. ## 4. Parameters and calls (R4) **R4. Parameters are lent.** `fn f(xs: List)` reads the caller's list, with no copy and no move. The callee can read it, pass it on, lend from it, but never keep it (R8). `fn f(mut xs: List)` may also write it, and the call says so: `f(mut a)`. A method receiver is the same, with no marker at the call: `fn add(mut self, x: Int)` is called as `st.add(x)` and needs `st` to be a mutable place. ```cp fn grow(mut xs: List): xs.push(1) var a = List() grow(mut a) // fine grow(a) // error: grow takes `mut xs`; write grow(mut a) let b = List() grow(mut b) // error: b is a let; declare it var ``` A `mut` parameter is a place: the callee may assign it whole (`xs = List()`), which replaces the caller's value. **Generated constructors move.** `S(a, b)` and struct literals take their arguments by value (R2): an owned argument moves in, a lent argument makes the struct lent (R6). That is how a library struct holds a closure or a source: `Filter(self, keep)`. A custom constructor (`SegTree(max, a)`) is a static fn and follows R4/R5 below (chapter 2.6 has the one rule). ```cp struct Holder: xs: List var a = List(1, 2) let h = Holder(a) // a moves into h print(a.len) // error: a was moved into h on line 3; write Holder(a.clone()) ``` ## 5. Returns (R5) **R5. A fn returns an owned value, unless it is declared `lends`.** Returning moves, and is O(1). Returning a parameter, part of one, or anything built from one is returning a lent value, which needs `lends` in the signature (§6), or `.clone()`. ```cp fn make(n: Int) -> List: var xs = List() for i in 0..n: xs.push(i) xs // moves out: O(1) fn same(xs: List) -> List = xs // error: returns the lent parameter xs; return xs.clone(), or declare `lends List` ``` **Custom constructors follow R5 too.** A static-fn constructor is a fn, so its parameters are lent for the call and its result is owned unless it says `lends`. An owned result never keeps its source busy: the source is free again when the call returns. ```cp let t = Rooted(g, root: r) // reads g, owns its arrays: g is free let fast = LcaTable(t) // reads t, owns its table: t is free let ev = xs.filter(p) // filter is `lends`: xs is lent while ev lives ``` The stdlib picks with one rule: **a result owns its data when copying what it needs fits within the cost the fn already documents; it lends only when copying would cost more than building**, which is the case for O(1) views and adapters (`a[l..r]`, `.filter`, `g.weighted(f)`). So every O(n)-or-more build (`Graph.directed`, `Rooted`, `LcaTable`, `Lift`, `Centroids`, `t.virtual`, `SegTree`) returns an owned value, and `lends` in a signature always means "O(1), and borrows". Sharing a domain (`V`, `t.Pre`) is not a lend: domains are types, so a table indexed by `t.Pre` holds nothing of `t`. ## 6. `lends` fns and projections A fn whose result borrows from its arguments declares it: ```cp fn window(xs: [V]Int, l: V) -> lends [V]Int = xs[l..] // read lend pub fn at(mut self, i: D) -> lends mut T // a writable place fn pick(a: List, b: List) -> lends(a) List // borrows only a ``` - **Meaning.** The result is a lent value whose sources are every non-plain parameter, or the ones named in `lends(...)`. The body is checked against that: lending from `b` in `pick` is an error in `pick`. (R05.6.1) - **Desugaring.** A call passes the rest of the caller's block as a callback: `let w = window(a, l); use(w)` is `window(a, l, w => use(w))`. That is why no lifetime is needed: the lent value never outlives the caller's block. `return` and `break` in that rest-of-block act on the caller, because it is the caller's code. (R05.6.2) - **`lends mut T`** is a place: the caller can assign through it, `a[i] = 5` is `a.at(i) = 5`. Code after the tail expression in the body runs when the caller is done (write-back: a `SegTree` repairs ancestors). (R05.6.3) - **Indexing, slicing, `.rev`, `.map`, `.filter` are all `lends` fns.** So `let row = rows[i]` and `let w = a[l..r]` are lent values by this rule, with nothing special about `[]`. (R05.6.4) ## 7. Lent values (R6 to R8) **R6. What is lent.** A value is lent when any part of it is lent: - a parameter (R4), and anything a `lends` fn returns (§6); (R05.7.1) - a struct, tuple or enum with a lent field (`Filter(self, keep)`); (R05.7.2) - a generator value with a lent argument (`dfs(g, s)`, `dfs(mut seen)`); (R05.7.3) - a loop item, for the iteration (§9); (R05.7.4) - a closure or nested fn that captures a local `var`, a local heap value or a parameter (§10). (R05.7.5) It is a `mut` lend when any part is a `mut` lend. Its **sources** are the variables its parts borrow, transitively. Everything else is owned. **R7. While a lent value is alive, its sources are lent.** Alive means from where it was made to its last use (not to the end of the block). - **Read lend:** the sources can be read, but not written, resized or moved. (R05.7.6) - **`mut` lend:** the sources can't be touched at all except through it. (R05.7.7) ```cp var a: [V]Int = 0 let w = a[l..r] a[l] = 5 // error: a is lent to w until line 4 print(w.sum()) ``` Swap lines 3 and 4 and it compiles: `w` is dead before the write. **Binding a lent value.** `let ys = xs` with `xs` lent re-lends it (same sources, no copy). `var ys = xs` with a lent heap value is an error suggesting `xs.clone()`: a `var` owns what it holds, and taking ownership would move out of the caller's value. Plain values copy either way. **R8. Where a lent value may be kept.** A lent value may be bound by `let`, put in a field, or pushed into a container, **if that storage dies no later than every source**: it is declared in the same block as the sources or a block nested inside it, and after them. It may never be: - returned, except from a fn declared `lends` (§6); (R05.7.8) - stored into anything reached through a parameter (a `mut` parameter's storage belongs to the caller); (R05.7.9) - stored in a top-level `var`. (R05.7.10) ```cp let ws = read<[V]Int>() var st = SegTree((i, j) => if ws[i] <= ws[j]: i else: j, [V] v => v) // fine: st dies before ws ``` ```cp var best = List() for r in rows: if r.len > best.len: best = r // error: r is lent for one iteration; write r.clone() ``` ```cp fn keep(mut out: List, s: Str): out.push(s) // error: out belongs to the caller; push s.clone() ``` ## 8. Overlap and order (R9 to R11) **R9. Two live lends of overlapping places, one of them `mut`, are an error unless the compiler proves them apart.** - Different fields never overlap: `f(mut s.left, mut s.right)` is fine. (R05.8.1) - Two elements need the projection's `disjoint` law proven from facts at that point (`if i != j`, `assert`, `i < j`, value ranges, distinct literals). Two slices need the ranges proven apart: `solve(mut a[l..m], mut a[m..r])` is fine. (R05.8.2) - Different projections of one receiver always conflict (`g.row(r)` and `g.col(c)`). (R05.8.3) - A container's length can't change while any place in it is lent: `let x = mut xs[i]` then `xs.push(..)` is an error. (R05.8.4) ```cp swap(mut a[i], mut a[j]) // error: a[i] and a[j] may be the same element if i != j: swap(mut a[i], mut a[j]) // fine ``` **R10. A call is one access to everything it touches:** its arguments, the variables the called fn or nested fn captures, and the captures of every closure argument, all for the duration of the call. Those accesses must not conflict with each other (R9) or with live lends (R7). A capture is borrowed at each call, not for the closure's whole life, so a closure that writes `cnt` can be called, then `cnt` read, then the closure called again. ```cp xs.sort(by: x => xs.len - x) // error: sort holds xs `mut` for the call, and the closure reads xs ``` ```cp var a: [V]Int = 0 fn clobber(): a[V.first!] = 0 let part = a[l..r] clobber() // error: clobber writes a, and a is lent to part until line 5 print(part.sum()) ``` The effect is computed through any depth of calls (`outer` calling `clobber` is the same error), in one linear pass over the call graph. **R11. Evaluation order.** Operands run left to right. An assignment or compound assignment runs its right side first, then the target's index expressions, then lends the target for the write, so each lend ends before the next starts. `a.push(a.len)`, `a[i] = a[j] + 1` and `cnt[a[i]] += 1` are fine. `xs[0] = xs.pop()!` and `a[l] += inc(mut a[l])` also compile, with a lint: a right side that writes the target's container is legal but easy to misread (`inc` runs first, then the new `a[l]` gets its result added). ## 9. Generators and views (R12) A **view** is a lent value that is a sequence (`a[l..r]`, `a.filter(p)`, `a.map(f)`): an ordinary struct whose `src` field holds a lent source, so R6 to R8 cover it with nothing extra. The same struct built from an owned value owns it (`Filter(xs, p)` moves `xs`). A **generator value** is a generator fn with its arguments filled in: `let g = dfs(graph, s)` runs nothing. It holds its arguments like a struct holds fields, so `divisors(12)` is owned (it can be stored or returned), `dfs(graph, s)` is lent from `graph`, and `dfs(graph, s, mut seen)` is a `mut` lend of `seen`. **R12. Walking.** `for x in g: B` calls the generator with `B` as its loop body; every walk reruns it from the top, with fresh locals and the current state of its arguments. - The generator's lends are live for the walk, so `B` may read a read-lent source but not write it, and may not touch a `mut`-lent one. (R05.9.1) - The item `x` is the body's parameter: plain items copy, heap items are lent for one iteration (R8: keep one with `x.clone()`). (R05.9.2) - `break`, `continue` and `return` in `B` act on the loop and the enclosing fn, through recursive generators too. (`x?` never transfers control: it propagates `None` within its expression, chapter 2.) (R05.9.3) - Walking a `mut`-lent generator value twice is legal and linted: the second walk sees what the first changed. (R05.9.4) ```cp var seen: [V]Bool = false for v in dfs(g, s, mut seen): seen[v] = true // error: seen is lent `mut` to the dfs for the whole loop ``` ```cp for x in xs: xs.push(x) // error: xs is read-lent to the loop for i in xs.keys: xs.push(xs[i]) // fine: xs.keys is a plain range, fixed before the loop ``` ## 10. Closures and nested fns A lambda (`x => ...`, block lambdas included) and a nested `fn` are the same thing: a fn value with captures. There is no `mut fn` (decision 5.10): a nested fn declared after a `var` may read and write it. - **What is captured.** Plain `let`s are copied in. Local `var`s, local heap values and parameters are captured by reference. Top-level names are not captures; any fn may use them (a fn that writes a top-level `var` has that effect at every call, R10). (R05.10.1) - **Mode.** A fn value that captures by reference is lent (R6), with the captured variables as sources, so R8 limits where it can be kept: it can be bound, passed, stored in a local `var` or struct, but not returned or stored past those variables. A captured variable can't be moved while the fn value is alive. (R05.10.2) - **Calls.** Captures are borrowed per call (R10), and `mut` captures are exclusive for that call: passing `mut a[l]` to a fn that also writes the captured `a` is an error. (R05.10.3) - **Arguments.** A closure passed to a fn is a parameter there (R4): the callee can call it but can't keep it, so every closure argument is inlined and costs nothing. Only constructors keep closures (§4). (R05.10.4) - **Recursion.** Nested fns and `let`-bound lambdas may call themselves. (R05.10.5) - **Spelling differences only.** A nested `fn` can take explicit type parameters (`fn go(..)`), attributes (`@memo`) and sibling fns in the same block, so mutual recursion works. A lambda infers its parameter types from where it is used, and its `let` name is visible only from its own body on. Both can be generators (`-> yields T`). (R05.10.6) - **`return`** inside a lambda returns from the lambda. (Non-local exit from closures is deferred, decision 126; use a `for` over a generator.) (R05.10.7) - **`@memo`** fns may not capture a `var` they could see change. (R05.10.8) ```cp var cnt = 0 let inc = () => cnt += 1 inc() print(cnt) // fine: inc borrows cnt only during each call inc() ``` ```cp fn counter() -> (() -> Int): var c = 0 () => c // error: the lambda captures local c, so it can't be returned ``` ## 10a. Caches: `@cache` fields A method that is logically a read can write a field marked `@cache` through a read `self`: path compression in `Dsu.find`, lazy tables in `Comb`, tag pushes in a lazy segment tree query, splay-tree reads. ```cp pub struct Dsu: @cache parent: [V]V size: [V]Int pub fn find(self, x: V) -> V: let p = self.parent[x] if p == x: return x let r = self.find(p) self.parent[x] = r r ``` Checked by the compiler (these make it memory-safe): - **C1. No lend escapes.** No `lends` result, projection or stored value borrows the field, so no outside view can see it change (as with Rust's `Cell`). (R05.10.9) - **C2. Only the struct's own methods write it.** Outside code can't, even through `mut`. (R05.10.10) - **C3. Inside the struct, a cache write is a `mut` access to the field.** A method walking `self.parent` can't call `self.find` partway through. Only callers are relaxed. (R05.10.11) - **C4. No unknown calls while the field is lent.** A method holding a lend into the field may not call a closure or fn parameter: it could capture the struct and call `find`, writing under the method's view. (R05.10.12) - **C5. Derived `==`, `hash`, `Ord` and `print` skip `@cache` fields.** Otherwise `d1 == d2` could flip after a `find`; a struct that needs them compared writes the impl by hand. (R05.10.13) Promised by the author (this makes it correct): - **P1. Cache writes change no answer.** Every sequence of public calls gives the same results as if each cache write through a read `self` were undone at method exit. Equivalently, the abstract value (the partition, the factorials) never changes. (R05.10.14) Stress runs check P1 with a cold mode that undoes those writes at method exit and compares output with a normal run; P1 is exactly what makes the two comparable, so no struct needs its own checker. - Shared ownership (two owners of one mutable value) stays out: pass `mut x` to each call, or capture `x`. ```cp let d = build_dsu(edges) // a let for v in V: print(d.find(v)) // fine: find takes read self ``` ## 11. Top-level state The file body is a fn (decision 6.1). Top-level `let`s are visible to every fn; a top-level `var` is visible to fns declared after it, which may write it. R10 treats such a fn's use of a top-level `var` as part of every call to it. Nothing lent may be stored in a top-level `var` (R8). ## 12. How to evaluate a snippet 1. **Mark each binding** owned or lent (R6). For lent ones, note the sources and the line of last use. 2. **Moves:** any use of a heap variable after it moved (R2)? 3. **Mutation:** is every write, `mut` argument and `mut self` call on a mutable place (R3)? 4. **Live lends:** between each lent value's creation and last use, does anything write, resize or move a source, or touch a `mut`-lent source (R7)? Include writes done by called fns and closures (R10). 5. **Keeping:** is a lent value returned without `lends`, stored through a parameter or globally, or stored somewhere that outlives a source (R8)? 6. **Overlap:** does any call or statement hold two overlapping places with one `mut`, without a proof they differ (R9)? 7. **Order:** evaluate right side, then target indices, then the write (R11); only lends alive at the same moment can conflict. If every step passes, it compiles. ## 13. What this page settles Earlier documents disagree with each other in places. This page picks: | Topic | Earlier text | Now | Why | |---|---|---|---| | Copy spelling | `.copy()` (5.2, plan/14) | `.clone()` | 128, 141 and `std.seq` already say `clone` | | Mutating nested fns | `mut fn` (plan/14, plan/15) | any nested fn after a `var` | 5.10 deleted `mut fn` | | Stored pull iterators | `Iterator`, pull for `zip` (4.2, 4.4) | push only; lockstep is `List(g)` | 126, 141 | | Plain vs heap | "≤ 16 bytes copies" (3.5) | "no heap part" copies | size must not change meaning | | Read-lent sources | "none changes length" (W4) | no writes at all | plan/14's exclusive-mutation rule; red-team case 1 | | Lent values in `var`s, fields, containers | never (5.14, 141 rule 3) | allowed when the storage dies no later than its sources | `var st = SegTree(V, op: closure over ws)` must work | | Lent struct construction | only inside projection bodies (plan/19 §5.1) | anywhere | 141 makes view structs plain | | Closure captures | held for the closure's life (implied by 141 rule 4) | borrowed per call | calling a counter closure, reading the counter, calling it again must work | | Inline closures reusing the callee's `mut` borrow | allowed (5.4) | withdrawn | its client (`undo`/`with`) was deleted (5.8); it was the one unsound corner | | Mutable `let` aliases | left out of the first version (plan/19 §5.3) | `let p = mut a[i]` allowed | implemented and used by ports | | `let row = rows[i]` on a heap element | unclear (move? copy?) | a read lend | `at` is a `lends` fn; no special case for `[]` | | Interior mutability | `Comb` alone had it (19.10) | `@cache` fields, for any struct | no stdlib privilege; `Dsu.find` needs it too | ## 13a. Why, compared with Rust, and limits **Why mutation XOR access.** Every aliasing bug needs a writer and another live view of the same data at once; the rule forbids exactly that pair. It removes four classes: 1. **Invalidation:** a view depends on length or storage and a write moves it (`for x in v: v.push(x)`, holding `v[0]` across a push). 2. **Stale reads:** a reader assumes the data holds still (a comparator reading the array being sorted, a slice summed while a callee writes). 3. **Self-aliasing:** two names for one thing where code assumed two (`merge(mut a, mut b)` that clears `b` when `a` is `b`). 4. **Lost locality:** without it, "nothing here touched `x`" needs whole-program knowledge, for the reader and the optimizer. Two `mut` lends are banned because every `mut` lend also reads. Values, not objects, already removes most aliasing; XOR is checked only on lends. **Compared with Rust.** Our lends are second-class: never in a type, never past the caller's block. - No `&T`, `&mut T` or lifetimes; a fn says `lends` / `lends(x)` instead. - Parameters are lent or `mut`; a callee never takes ownership. - Plain values copy and heap values move by rule (no `derive(Copy)`). - One closure kind; captures are borrowed per call, not for the closure's life, so `let inc = () => cnt += 1; inc(); print(cnt); inc()` compiles. - Projections are inline callbacks, so they can repair after a write. - `if i != j` proves disjoint `mut` places; no `split_at_mut`. - Push generators, so no lending-iterator problem. Closest relatives: Hylo (mutable value semantics, `inout`, yield subscripts), Swift (non-escaping closures, exclusivity, `_modify`), Mojo (`read`/`mut`/`owned`), and second-class values (Osvald et al., 2016). **Not expressible, on purpose:** closures that outlive their captures (returned counters, stored callbacks); two owners of one mutable value (pass `mut x` per call); a paused generator (use `List(g)` for lockstep); a callee that takes ownership (`mut xs` plus `xs.take()`); pointers between nodes (domain indices). Closures of different types never share a container, since each closure has its own type and nothing lowers to `std::function` (see R06.2.5): use an enum of the cases. **Sharp edges** (errors and hovers must carry these): 1. `let` copies a plain element, lends a heap element, moves a variable. 2. The mode is not in the type: `xs.filter(p)` is lent, `Filter(xs, p)` owned; hover shows which. 3. Passing `mut seen` freezes it for the value's life; capturing it freezes it per walk. 4. A later use extends a lend, so an added `print` can break a write between; a nested fn that writes `a` conflicts at its calls. 5. Declaration order matters for R8. 6. A record gaining a heap field stops copying and starts moving; a lint or hover badge for plain-ness is open. 7. Re-walking a `mut`-lent generator reruns it against changed state (linted). **Lowering, in one line** (the companion doc is paused): a struct's code is written once; in C++ each mix of owned and lent fields the program actually builds is one template instantiation (owned by value, lent by reference or span), so usually one or two per struct. ## 14. Exercises Does each snippet compile? `V`, `a: [V]Int`, `g: Graph`, `rows: List>` and `i, j, l, r: V` are in scope unless the snippet declares them; `a` and `rows` are `var`s. Answers follow each one. **1.** ```cp var xs = List(1, 2) let ys = xs print(ys.len) ```

AnswerYes. xs moves into ys (R2); xs is never used again.
**2.** ```cp var xs = List(1, 2) let ys = xs print(xs.len + ys.len) ```
AnswerNo. xs is used after it moved (R2). Fix: let ys = xs.clone().
**3.** ```cp let p = (x: 3, y: 4) let q = p print(p.x + q.y) ```
AnswerYes. A record of Ints is plain and copies (R1).
**4.** ```cp fn twice(xs: List) -> List: var ys = xs ys.extend(xs) ys ```
AnswerNo. xs is a lent parameter; var ys = xs would take ownership of a lent heap value ("Binding a lent value", before R8). Fix: var ys = xs.clone().
**5.** ```cp fn grow(mut xs: List): xs.push(0) let b = List() grow(mut b) ```
AnswerNo. b is a let, not a mutable place (R3).
**6.** ```cp let w = a[l..r] print(w.sum()) a[l] = 5 ```
AnswerYes. w's last use is before the write (R7).
**7.** ```cp let w = a[l..r] a[l] = 5 print(w.sum()) ```
AnswerNo. a is read-lent to w until line 3 (R7).
**8.** ```cp let row = rows[i] rows.push(List()) print(row.len) ```
AnswerNo. row is a lend of rows (§6), and pushing resizes a source (R7). Fix: rows[i].clone(), or print first.
**9.** ```cp var longest = List() for row in rows: if row.len > longest.len: longest = row ```
AnswerNo. row is lent for one iteration and longest outlives it (R8, R12). Fix: longest = row.clone(), or keep the index with rows.argmax(by: r => r.len).
**10.** ```cp for x in rows[i]: rows[i].push(x) ```
AnswerNo. rows[i] is read-lent to the loop (R12).
**11.** ```cp for k in rows[i].keys: rows[i].push(rows[i][k]) ```
AnswerYes. .keys is a plain range taken before the loop; each statement's lends end with it (R11).
**12.** ```cp swap(mut a[i], mut a[j]) ```
AnswerNo. Nothing proves i != j (R9). Fix: if i != j: or a.swap_at(i, j).
**13.** ```cp fn solve(mut lo: [V]Int, mut hi: [V]Int) = todo let m = l.next(5)! solve(mut a[l..m], mut a[m..r]) ```
AnswerYes. The ranges meet at m and can't overlap (R9).
**14.** ```cp let p = mut a[i] p += 1 a[j] = 0 p += 1 ```
AnswerNo. a is mut-lent to p until line 4 (R7). Without line 4 it compiles.
**15.** ```cp a.push(a.len) cnt[a[i]] += 1 ```
AnswerYes. Arguments and indices are evaluated before the target is lent (R11). (Assume a is a List<Int> here and cnt a var map.)
**16.** ```cp fn inc(mut x: Int) -> Int: x += 1 x a[l] += inc(mut a[l]) ```
AnswerYes, with a lint. The right side runs first, so a[l] is incremented, then inc's result is added to the new value (R11).
**17.** ```cp var cnt = 0 let bump = () => cnt += 1 bump() print(cnt) bump() ```
AnswerYes. Captures are borrowed per call (R10).
**18.** ```cp fn counter() -> (() -> Int): var c = 0 () => c ```
AnswerNo. The lambda captures local c, so it is lent and can't be returned (R5, R8).
**19.** ```cp fn adder(k: Int) -> (Int -> Int) = x => x + k ```
AnswerYes. k is plain, so it is copied in; the lambda is owned (§10).
**20.** ```cp let ws = read<[V]Int>() var st = SegTree((x, y) => if ws[x] <= ws[y]: x else: y, [V] v => v) st[i] = i ```
AnswerYes. st is lent from ws and declared after it in the same block (R8). (SegTree's element type here is V.)
**21.** ```cp var xs = List(3, 1, 2) xs.sort(by: x => xs.len - x) ```
AnswerNo. sort holds xs mut for the call, and the closure argument reads xs (R10).
**22.** ```cp fn clobber(): a[l] = 0 let part = a[l..r] clobber() print(part.sum()) ```
AnswerNo. clobber writes a while it is lent to part (R7, R10).
**23.** ```cp var seen: [V]Bool = false for v in dfs(g, s, mut seen): if seen[v]: print(v) ```
AnswerNo. seen is mut-lent to the generator for the whole walk, so even reading it is excluded (R12). Fix: let the generator report it, or materialize the walk with List(...) first.
**24.** ```cp var seen: [V]Bool = false let walk = dfs(g, s, mut seen) let n1 = walk.count() let n2 = walk.count() ```
AnswerYes, with a lint: the second walk reruns the DFS against the seen the first one filled, so n2 is 0 (R12).
**25.** ```cp let gs = List(divisors(12), divisors(30)) for d in gs[0]: print(d) ```
AnswerYes. divisors(12) captures only an Int, so it is owned and can live in a list (§9).
**26.** ```cp fn tail(xs: [V]Int, l: V) -> [V]Int = xs[l..] ```
AnswerNo. It returns a lent slice without lends (R5). Fix: lends [V]Int, or return the range l.. and slice at the caller.
**27.** ```cp fn pick(x: List, y: List) -> lends(x) List = y[..] ```
AnswerNo. The body lends from y but the signature says only x (§6).
**28.** ```cp fn keep(mut out: List, s: Str): out.push(s) ```
AnswerNo. s is lent, and out belongs to the caller (R8). Fix: out.push(s.clone()).
**29.** ```cp struct Pair: left: List, right: List fn both(mut x: List, mut y: List) = todo var p = Pair(List(), List()) both(mut p.left, mut p.right) both(mut p.left, mut p.left) ```
AnswerLine 4 compiles (different fields, R9); line 5 doesn't (the same place twice).
**30.** ```cp var depth: [V]Int = 0 fn visit(v: V, from: ?V): for (to: u, ..) in g[v]: if u != from: depth[u] = depth[v] + 1 visit(u, v) visit(V.first!, None) print(depth.max()) visit(V.first!, None) ```
AnswerYes. A nested fn after a var may write it; the capture is borrowed only during each call (§10, R10).
**31.** ```cp var xs = List(1, 2) let f = () => xs.len let ys = xs print(f()) ```
AnswerNo. xs is captured by f, which is alive until line 4, so it can't move (§10).
**32.** ```cp let evens = a.filter(x => x % 2 == 0) let total = evens.sum() let best = evens.argmax() a[l] = 0 ```
AnswerYes. Two walks of a read-lent view are fine; evens is dead before the write (R7).
**33.** ```cp fn evens(xs: [V]Int) -> lends Filter<[V]Int, Int -> Bool> = xs.filter(x => x % 2 == 0) for x in evens(a): a[l] += x ```
AnswerNo. The result borrows a for the loop, and the body writes a (R12).
**34.** ```cp var a2 = a.clone() for x in a.filter(x => x > 0): a2[l] += x ```
AnswerYes. The loop lends a; the body writes the separate a2.
**35.** ```cp var best: ?[V]Int = None for (l2, r2) in queries: best = a[l2..r2] print(best!.sum()) ```
AnswerYes: best is declared after a's declaration in an enclosing block, so it dies first (R8), and a stays read-lent until line 4. The idiomatic version keeps the range (var best: ?Range<V>) so a isn't frozen meanwhile.
--- # 6. Functions, closures and generators URL: /docs/ref/core/06-control-functions This is the normative specification ([source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/core/06-control-functions.md)). For a gentler introduction, start with the [guides](/docs/guides). Status: draft for 0.3.0. Ownership of captures and lends is chapter 5, which is authoritative; this chapter gives the forms and their meaning. Sources: archived `design/spec/14-16`, `plan/15-program-structure.md`; decisions 126, 127, 129, 138, 141, 144. ## 6.1 Functions ``` fn dist(a: P, b: P) -> Int = abs(a.x - b.x) + abs(a.y - b.y) fn solve(n: Int, mut seen: [V]Bool; limit: Int = 10) -> ?Int: ... ``` - One-line `= expr` or a block whose last expression is the value. `return` is for early exits. (R06.1.1) - Parameters are lent for the call; `mut` parameters may be mutated (or drained) and are marked `mut` at the call: `solve(n, mut seen)`. The method receiver needs no marker at the call. (R06.1.2) - A parameter of a `fn` or a lambda may be a pattern, as in `for`: `(mut d, (u, v)) => d.unite(u, v)`. `mut` marks the whole parameter. (R06.1.3) - A lambda with k parameters, passed where the callee expects a function of one k-tuple, unpacks it: `(V, V).all((u, v) => ...)` and `a.items.filter((i, x) => ...)` mean `((u, v)) =>` and `((i, x)) =>`. The callee's function type decides; a lambda that wants the whole tuple takes one parameter (`p => p.0`). This is not overloading: the signature is fixed and only the lambda's spelling adapts (decision 159). (R06.1.4) - Named and positional arguments, defaults, named-only parameters after `;`, and a variadic `..xs: Ts` tuple parameter. Options are always named (`by:`, `desc`), never `_by` twins (decision 60). (R06.1.5) - No overloading by type: one name and label set has one generic signature (decision 127). Operators are functions: `fn (a: Frac) + (b: Frac) -> Frac`. (R06.1.6) - Functions hoist within their block; every capture must be initialized before the first call. (R06.1.7) - A `fn` passed where a function of fewer parameters is expected takes only those, when every omitted trailing parameter has a default; the defaults fill them: `vis.map(yes)` is `vis.map(b => yes(b))`. An omitted parameter without a default is a type mismatch (E0302). (R06.1.8) ## 6.2 Nested functions and lambdas Nested `fn`s and lambdas are the same thing for every rule; they differ only in spelling (decision 144): ``` fn go(v: V): // nested fn: recursion by name seen[v] = true for u in g.next(v) if not seen[u]: go(u) let fact = n => if n == 0: 1 else: n * fact(n - 1) // recursive lambda xs.sort(by: p => (p.x, desc(p.y))) on_remove: (v, a) => cnt[a] -= 1 // body may be an assignment by: x => // block lambda let k = key(x) (k.0, -k.1) ``` - **Captures act as call-time arguments.** A closure holds no lend between calls: each call lends what it reads and mutably lends what it writes, for the call's duration. So a closure may mutate captured `var`s, two closures may capture the same `var`, and the borrow rules are checked at each call site (chapter 5). (R06.2.1) - A captured variable cannot be moved while the closure is alive, and a closure cannot outlive what it captures (it cannot be returned past them, stored in an outer `var`, or put in a longer-lived field). (R06.2.2) - A `let`-bound lambda may call itself; a `var` binding cannot. When recursion leaves the return type open, annotate: `(n: Int) -> Int =>`. (R06.2.3) - There is no `pure` and no `mut fn` marker. Purity that a library needs (lazy `map`, `@memo`) is a documented contract checked by lints and stress, not a type. (R06.2.4) - Function types are `(A, B) -> R`. Every call with a known function value is specialized; there is no indirect call and no `std::function` (chapter 13). (R06.2.5) ## 6.3 Generators A generator is a function that pushes elements to its caller's loop body: ``` fn divisors(n: Int) -> yields Int: for d in 1..=n.isqrt() if n % d == 0: yield d if d * d != n: yield n / d for d in divisors(n): ... let s = divisors(n).filter(d => d % 2 == 0).sum() ``` - A generator **value** is a recipe: a call with every argument but the loop body filled in. Nothing runs until something walks it (`for`, a fold, `.collect()`), and each walk reruns it. Walking a value twice is legal; walking one that holds a `mut` lend twice is linted. (R06.3.1) - A generator value built from lent arguments holds those lends until its last use, like a struct built from them (chapter 5). (R06.3.2) - The loop body may `break`, `continue`, `return`, use labels and loop `else`, even when the generator is recursive (decision 126). A non-recursive generator inlines into the loop; a recursive one gets a hidden stop path only in specializations whose body can exit. (R06.3.3) - A body steers its generator through the yielded item, read after `yield` returns: `step.prune()` skips a DFS subtree. Enter/exit walks yield events (`Enter(v, via:)`, `Exit(v, via:)`, `Again(from, via)`). (R06.3.4) - Generators are push-only; there is no cursor. Lockstep over two generators is `List(g)` first, a visible allocation. (R06.3.5) - Sequences, views, chains and capabilities are chapter 7. ## 6.4 Decorators `@d(args)` before an item. The set is closed, each documented by its library or by this spec: - `@memo(array)` / `@memo(map)`: cache a function. The storage is spelled, never picked (round 3): `array` needs every parameter typed by a bounded type (domain, cut, range, `Bool`, enum) and allocates the dense table on the first call, `map` uses an open-addressing hash map. A parameter bound may mention earlier parameters (`j: 0..=i`); the table is then jagged. The cache lives as long as the declaring block (per test case at top level below `@!multitest`). A memo function may not do I/O or mutate captures; a write to something it captured while the cache lives is an error. `cpl explain` shows table bytes. (R06.4.1) - `@get`: an O(1) read-only method called without parentheses. (R06.4.2) - `@test`, `@alt(f, caps)`, `@gen`, `@check`, `@interactor`: tool roles (`tools/stress.md`); the item is otherwise unchanged. (R06.4.3) - `@cache` on a struct field: compiler-safe interior mutability with an author promise of logical correctness (chapter 5 §10a). (R06.4.4) - `@trusted:` blocks and `@cpp` items: the unsafe tier (chapter 9). - `@grader(...)`: judge entry points (chapter 10). - `@laws(sample: n)`: stress sampling of a type's laws. - `@tag(lit)` on an enum variant: the token it reads and prints as (chapter 2). - `@droppable`: the result may be dropped without the unused-result lint. Dropping a non-unit result is that lint (a warning); dropping a `?T` is an error (see R02.4.7). (R06.4.8) User libraries declare their own decorators as ordinary generic functions over function types, and their own tool roles with `marker` (chapter 12, W-list). ## 6.5 Where state lives - Top-level bindings above `@!multitest` are shared by every test case; everything below is per case, including `@memo` caches and fresh types. (R06.5.1) - A nested function is the way to split a long solution: each chunk is a nested fn over the test's state. Any function is a *part* that stress and `cpl locate` can test alone (`tools/stress.md`). --- # Round 2: sequences and views URL: /docs/ref/core/07-sequences This is the normative specification ([source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/core/07-sequences.md)). For a gentler introduction, start with the [guides](/docs/guides). Built on round 1: arrays are `[D]T`, ranges are runs of a domain with cut ends, `.first`/`.last` are optional. ## Key decisions 1. **Generators are the only iterator.** `-> yields T`, no `next()`; values are pushed into the loop body, so they compile to the hand-written loop. `break`/`return` work through them; lockstep is `List(g)`. (R07.1.1) 2. **Six capabilities.** `Seq` walks; `Keyed` walks `(key, x)`; `Sized` has O(1) `.len`; `Bidir` walks backwards; `Indexed` adds O(1) `s[i]` and `.keys`; `IndexedMut` makes `s[i]` a place (POWERS W4). Adapters keep `Indexed` when they can stay O(1) (slices, `.rev`, `map`, `take`/`drop`, `zip`); `filter`, `take_while` and generators are `Seq`. (R07.1.2) 3. **Laziness is explicit.** A chain reruns on every walk. Allocation happens only at `.collect()`, a comprehension or `List(...)`. Lint flags a chain walked twice (sharper when it holds a `mut` lend) and side-effecting closures. (R07.1.3) 4. **Identity everywhere.** Every slice keeps its source's keys (`a[l..=r][i] == a[i]`, `s[2..5][3] == s[3]`), and library functions answer in the keys they were given. `first`, `nth(k)` and `rebase` cover relative access. (R07.1.4) 5. **Views are lent values with the rules of `mut a[i]`.** A value built from a lent part is lent; no lifetime annotations. It is kept only where R05.7.8 to R05.7.10 allow (storage that dies before its sources) and returned only by a fn declared `lends`. In-place verbs work on views (`a[l..=r].sort()`); each has a copying twin (`sorted`). (R07.1.5) 6. **Prefix scans are indexed by cuts.** `pre[c]` folds left of `c`; `pre[v]` folds through `v`. (R07.1.6) 7. **Costs show.** O(1) things are getters or views, allocation is named, options are named arguments (`max(by:)`), and there is no overloading. (R07.1.7) ## Terms Every word below means one thing in this doc, in the stubs and in errors. | Term | Means | Owns its elements? | Examples | |---|---|---|---| | **sequence** (`Seq`) | anything a `for` can walk, in order | either | everything in this table (R07.2.1) | | **indexed sequence** (`Indexed`) | a sequence that also has O(1) `s[k]`, `.keys` and `.len` | either | `[V]T`, `List`, `Str`, ranges, slices, `.rev` (R07.2.2) | | **key** | what an indexed sequence is indexed by: a domain position (`V`) or an `Int` offset (`List`, `Str`) | | `i: V`, `3` (R07.2.3) | | **collection** | a sequence that owns its elements; making one allocates | yes | `[V]T` arrays, `List`, `Str`, `Set`, `Map` (R07.2.4) | | **range** | a run of a domain, `l..r`; a sequence of positions or cuts with no data behind it (round 1) | nothing to own | `l..=r`, `..i`, `V.range` (R07.2.5) | | **view** | a sequence made from a source without copying it: O(1) to make, borrows the source, does its work as you walk or read it. Formally, a `Seq` built from a lent source, so it is a lent value (POWERS W4); there is no `View` trait and no marker on the struct | no | `a[l..=r]`, `a.rev`, `a.map(f)`, `a.filter(p)` (R07.2.6) | | **slice** | the view `a[r]`: one contiguous range `r` of an indexed source | no | `a[l..=r]`, `s[i..]`, `grid[r]` (a row) (R07.2.7) | | **adapter** | a method that turns a sequence into a view | | `.map`, `.filter`, `.rev`, `.take`, `zip` (R07.2.8) | | **chain** | adapters applied one after another; still a view, still lazy | no | `a.filter(p).map(f)` (R07.2.9) | | **generator** | a fn declared `-> yields T`; calling it gives a sequence that reruns the body on each walk | no | `divisors(n)`, `dfs(g, s)` (R07.2.10) | | **materialize** | copy a sequence into a new collection: the only allocation step | | `.collect()`, `List(s)`, `[f(x) for x in s]` (R07.2.11) | | **place** | something assignable: an element or a `mut` view | | `a[i]`, `mut a[l..r]` (R07.2.12) | How they relate: - **Two capabilities.** A view is indexed when its adapter can answer `w[k]` in O(1): slices, `.rev`, `.map`, `.items`, `zip`, `take`/`drop`. It is only a sequence (walk-only) otherwise: `filter`, `take_while`, `chain`, generators. (R07.2.13) - **Slices are the views that narrow keys.** Every other indexed view keeps its source's keys unchanged. (R07.2.14) - **Ranges are indexed sequences but not views:** they have no source. Slicing *with* a range gives a view. (R07.2.15) - **Lazy means a view or generator.** Its work happens at each walk or read, never up front. Materializing is the only step that does the work once and keeps the result. (R07.2.16) ```cp a[l..=r] // view of a over l..=r; a[l..=r][i] is a[i], i must be in l..=r s[2..5] // keeps keys: s[2..5][3] is s[3]; s[2..5].nth(0) is s[2] a[l..=r].keys // l..=r a.rev // walks a backwards; a.rev[i] is still a[i] a.map(f) // Indexed: (a.map(f))[i] is f(a[i]), O(1) per read a.items // (i, a[i]) pairs with a's own indices ``` ## The capabilities | Capability | What it guarantees | Examples | |---|---|---| | `Seq` | `for x in s` walks it in order; each `for` runs it from the start | generators, `s.filter(p)`, `chain(a, b)`, `g[u]` (R07.3.1) | | `Keyed` | `Seq` + `s.items` walks `(key, x)`; keys survive `filter` | everything `Indexed`, `s.filter(p)`, `s.take_while(p)`, `Map`, `g.keyed()`, `g.keyed(by: f)` (R07.3.2) | | `Sized` | O(1) `s.len` | collections, ranges, `Indexed` views, sets, maps (R07.3.3) | | `Bidir` | `s.rev` walks backwards; `s.last` is O(1) | everything `Indexed`, sorted sets, deques, `filter` over a `Bidir` (R07.3.4) | | `Indexed` | `Keyed` + `Sized` + `Bidir` + `s[i]` for `i: D` in O(1), `s.keys: Range` | `[D]T`, `List` and `Str` (`D = Int`), ranges, slices, `.rev`, `.map(f)`, `zip(a, b)` (R07.3.5) | | `IndexedMut` | `Indexed` + `s[i]` is a place: `sort()`, `swap`, slice assignment | `[D]T`, `List`, `Str`, `mut` slices (R07.3.6) | **Cost rule.** Views are O(1) to make and allocate nothing. A loop over them compiles to the loop you would write by hand. Anything that builds a container says so: a comprehension, `List(s)`, or a method named for its result (`sorted`, `tally`, `scan`). ## Slices: which keys survive Identity everywhere (decision 143; worked through in `04b-keys.md`): **an index names the same element everywhere it is valid.** A slice narrows the valid keys and never renames them, for domain arrays, `List` and `Str` alike, so an index taken from a view is valid on the source. ```cp let w = a[l..=r] let best = w.argmax()! // a position of a, usable anywhere for (i, x) in w.items: ... // i runs l..=r, not 0.. s[2..5][3] // s[3]; s[2..5][0] traps w.first!, w.nth(k) // first element; k steps from the start let t = w.rebase // O(1) view keyed by a fresh 0..w.len domain t.Idx ``` - **Keys in, keys out.** Library functions answer in the keys they were given: `s[l..].search(c)` is a key of `s`, `z_function(s[l..])` is keyed by `l..`, `a[l..r].scan(+)` by `a`'s cuts. Lengths and counts stay `Int`. (R07.4.1) - **Combining two sequences pairs them by walk order**: `==`, `<`, `starts_with`, `+`, slice assignment and `zip`. (R07.4.2) - **`[s.keys]x`** is a table over exactly `s`'s keys; `t.rekey(r)` re-keys equal-length cells onto `r` in O(1). (R07.4.3) - **Materializing counts from 0:** `.collect()`, `.sorted()`, `List(w)` and `Str(w)` build a new sequence keyed from 0. To keep `w`'s keys, build a table over them: `[w.keys] k => w[k]` (see R04b.1.6). (R07.4.4) - **Lints:** a literal index into a slice (`w[0]`), and a 0-based counter used as a slice key (`for k in 0..w.len: w[k]`); both suggest `first`, `nth`, `items` or `rebase`. An out-of-keys read traps naming the slice's keys. A raw `Int` into a domain slice is a compile error. (R07.4.5) | View | Indexed by | Walks | Cost | |---|---|---|---| | `a[r]` (`r: Range`; `a[j..i]` with cut ends is the piece) | `D`, only inside `r` | `r` in order | O(1) (R07.4.6) | | `a.rev` | `D` | backwards | O(1) (R07.4.7) | | `a.items` | `D`, gives `(i, a[i])` | in order | O(1) (R07.4.8) | | `a.map(f)` | `D`, gives `f(a[i])`, calling `f` on every read | in order | O(1); `f` per read (R07.4.9) | | `zip(a, b)` | `a`'s keys, pairing by walk order: the k-th of `a` with the k-th of `b` | in order | O(1) (R07.4.10) | | `w.drop(k)`, `w.take(k)`, `w.drop_last(k)`, `w.take_last(k)` | same as `w`, clamped: `w.drop(k)` is `w[w.l.next(k) ?? w.r..]` | in order | O(1) (R07.4.11) | | `grid[r]` | the column domain: row `r` of a `[R, C]T` | in order | O(1) (R07.4.12) | | `grid[rs, cs]` | `(R, C)` pairs inside `rs` × `cs`; `.items` gives `((x, y), v)` | row-major | O(1) (R07.4.13) | `zip` pairs by walk order and is keyed by its first argument; zipping a `[V]T` with an `[E]T` is still a type error. It stops at the shorter side. Writing a sequence into a range is slice assignment, not a zip: `q[start..] = suffix` copies in order, O(k), and traps in every build if the lengths differ. A view borrows its source. Through a `var` source a view is writable and every in-place verb works on it: `a[l..r].sort()`, `a[l..=r].reverse()`, `a[r].fill(0)`. Changing the source's length while a view is alive is a compile error (§128). ## Under the hood A view is a plain library struct built from a lent source: a reference plus the two end cuts as Ints. Direction and adapters are in the type, so nothing is decided at run time and nothing allocates. ```cp a[l..=r] // Slice{src: &a, lo: Int(l.l), hi: Int(r.r)} a[l..=r].rev.map(f) // Mapped>, F>, F the lambda's own type ``` | Written | Lowers to | |---|---| | `a[l..=r]`, `.rev`, `.map(f)` | build the struct, O(1) (R07.5.1) | | `w[i]` | debug: check `lo <= i < hi`; then `a[i]` (no offset: indices are kept) (R07.5.2) | | `w.rev[i]` | `a[i]`; only the walk order differs (R07.5.3) | | `a.map(f)[i]` | `f(a[i])`, inlined, per read (R07.5.4) | | `for x in w` | `for (i = lo; i < hi; ++i) body(a[i])` (R07.5.5) | | `for x in w.rev` | the same loop, `hi - 1` down to `lo` (R07.5.6) | | `w.keys`, `w.len` | `lo..hi`, `hi - lo` (R07.5.7) | | `List(w)` | the one allocation: a fresh 0-based copy (R07.5.8) | - **Lending: the rules of `mut a[i]`, over a range.** Any number of read views coexist with reads. A `mut` view excludes every other access to what it covers; two `mut` views not provably disjoint are a compile error (E0601). Halves at one cut (`mut a[..c]` and `mut a[c..]`, or `halve`'s two) are provably disjoint. A length change (`push`, `pop`, `clear`) while any view or place is alive is a compile error. (R07.5.9) - **Lifetime: second-class, no annotations.** A value is lent if any part of it is (a field, a capture, a generator argument), and a lent value lives until its last use in the block that made it. It passes into fns (arguments are always lent) and comes back only from a fn declared `lends`, whose result borrows every non-plain parameter unless narrowed: `fn window(xs: [V]Int, r: Range) -> lends [V]Int = xs[r]`, `fn pick(a: [V]Int, b: [V]Int) -> lends(a) [V]Int`. It never goes in a `var`, field, container, global or escaping closure. Keeping one is `List(w)`. (R07.5.10) - **Parameters.** A read-only `xs: [V]T` takes an array or any `Indexed` over `V` (a `mut` one, any `IndexedMut`); it is a template parameter, so each call site gets its own fused loop. `List` and `Str` parameters take only that container (chapter 4b, "User helpers"). (R07.5.11) - **Walk-only views.** `filter`, `take_while` and generators are `Seq` only: the `if` or the generator body is inlined into the `for`. (R07.5.12) ## Generators ```cp fn divisors(n: Int) -> yields Int: for d in 1..=n.isqrt(): if n % d == 0: yield d if d * d != n: yield n / d for d in divisors(n): if d > lim: break // break, continue, return, break 'outer, loop else ``` - **Push, not pull.** The generator runs and the `for` body runs at each `yield`, so a non-recursive generator inlines to a plain loop. Recursive generators (DFS, subset enumeration) work the same way, including `break` and `return` out of the body (§126). (R07.6.1) - **A generator value is a closure you walk instead of call.** `let g = divisors(n)` stores the fn and its arguments and runs nothing; each walk runs the body from the top, with fresh locals and the arguments as they are now. It is owned or lent by what it captured: `divisors(12)` is owned, `dfs(graph, s)` is lent, `dfs(mut seen)` is `mut`-lent. Walking a `mut`-lent one twice is legal (the second run sees what the first wrote) and linted. Keep the results with `List(g)`. (R07.6.2) - **Steering.** The yielded item may carry methods the generator reads after `yield` returns: `for step in dfs(g, s): if bad(step.v): step.prune()`. This is ordinary library code; any user generator can do it. (R07.6.3) - **No lockstep.** Two generators can't be walked in step, because each wants to own the loop. Materialize one (`List(g)`), or zip indexed sequences. `zip` takes only `Indexed`. (R07.6.4) ## Adapters (each makes a view: O(1), lazy) | Form | Result | Note | |---|---|---| | `s.map(f)` | `Indexed` if `s` is, else `Seq` | `f` runs on every read (R07.7.1) | | `s.filter(p)`, `s.take_while(p)`, `s.skip_while(p)` | `Seq` | (R07.7.2) | | `s.take(k)`, `s.drop(k)` | an O(1) view on an `Indexed`; a `Seq` otherwise | consuming a view from the front is `w = w.drop(1)` (R07.7.3) | | `chain(a, b)` | `Seq` | (R07.7.4) | | `s.adjacent` | `Seq<(T, T)>`, adjacent pairs | `@get`, O(1) per step (R07.7.5) | | `s.pairs()` | `Seq<(T, T)>`, every pair `x` before `y` | O(n²) to walk, so a call (R07.7.6) | | `s.with_prev` | `Seq<(?T, T)>`, starting `(None, first)` | path walks that treat the first step apart (R07.7.7) | | `s.cyclic_pairs` | `Seq<(T, T)>`, plus (last, first) | polygons, rings (R07.7.8) | | `a.windows(k)`, `a.chunks(k)` | `Seq` of views of `a` | each view keeps `a`'s indices (R07.7.9) | | `a.runs(by: k)` | `Seq` of views: maximal equal-key runs | `.keys` of each is its range (R07.7.10) | | `s.step(k)` | every k-th element | ranges and indexed (R07.7.11) | **Parentheses mean work.** Only O(1) members read without `()`: `@get` properties such as `.len`, and views and generators, which cost O(1) to make and are paid for as you walk them (`.rev`, `.items`, `.adjacent`, `.keys`, `g.edges`, `t.tour`). Anything that computes or allocates up front is a call, however few arguments it takes: `g.transpose()`, `t.centroid()`, `a.sorted()`, `.collect()`. The spec check rejects an `@get` whose documented cost isn't O(1) to make. ## Making containers ```cp [f(x) for x in s if p(x)] // List; reserves exactly when there's no filter [V] v => f(v) // [V]U, filled by f s.filter(p).map(f).collect() // end of a chain: the type the context expects, else List List(s) Set(s) Str(s) // conversions of anything that isn't a chain: List(0..n) ``` `.collect()` and the constructors are one operation, O(n) and allocating; the postfix form is for chains, the prefix form for single values. **Lazy chains redo their work on every consumption.** A `map` calls `f` on every read; a `filter` calls `p` on every walk. Lint flags a lazy chain walked twice, or built outside a loop and consumed inside it, and a lazy `map`/`filter` whose closure mutates anything (`rng.int(..)`, `count += 1`), suggesting `.collect()` or a comprehension. Walking a `mut`-lent value twice (`let a = dfs(mut seen)`, then two walks of `a`) gets the sharper message, since the second walk reruns against what the first wrote. ## Folds | Form | Result | Cost | |---|---|---| | `s.sum()`, `s.prod()` | `T`; empty is the identity | O(n) (R07.9.1) | | `s.fold(op)` | `T` when `op` has an identity (`+`, `max` on a bounded type, `gcd`), else `?T` | O(n) (R07.9.2) | | `s.min()`, `s.max()`, `s.min(by: k)` | `?T`, `None` when empty; first on ties | O(n) (R07.9.3) | | `s.count(p)`, `s.any(p)`, `s.all(p)` | `Int`, `Bool` | O(n) (R07.9.4) | | `s.find(p)`, `s.rfind(p)` | `?T`, linear scan (binary search is `r.first_true`) | O(n) (R07.9.5) | Position queries are folds over `a.keys`, because the keys are a range of positions. `argmin`/`argmax` are kept as the named form of the first line below (first on ties); there are no `first_at` or `order` twins: ```cp a.keys.min(by: i => a[i])! // argmin, first on ties a.keys.find(i => a[i] > x) // first position with a[i] > x, ?D a.keys.sorted(by: i => a[i]) // argsort: List a[l..r].keys.max(by: i => a[i])! // argmax inside a piece, still a position of a ``` ## Scans are prefix sums over cuts `a.scan(op)` gives a `Prefix`: n + 1 exclusive folds indexed by `D`'s cuts. Walking backwards gives suffix folds, indexed by the same cuts: ```cp let pre = a.scan(+) // pre[c]: fold of everything left of cut c let suf = a.rev.scan(+) // suf[c]: fold of everything right of cut c pre[r.r] - pre[r.l] // any range r pre[v] // a position: the fold through v, same as pre[v.r] prefix(a).fold(r) // same, as the `Prefix` struct (`+` only) pre[v.l] + a[v] + suf[v.r] // the whole array, split at position v ``` A `Prefix` takes both kinds of index and the types keep them apart: a cut folds what lies left of it, a position folds through itself. The inclusive query (`pref_min[v]`) is the common one and needs no `.r`. O(n) time and memory. This replaces `scan`, `suffix_scan`, `excl_fold`, `scan_in_place` and `Prefix(...)` construction. ## Ordering and grouping | Form | Meaning | Cost | |---|---|---| | `s.sort(by: k)`, `s.reverse()`, `s.dedup()`, `s.fill(x)` | in place: needs a `var` source; works on views | O(n log n), O(n), O(n), O(n) (R07.11.1) | | `s.sorted(by: k)`, `s.deduped()` | new `List` | same, allocates (R07.11.2) | | `s.group(by: k)` | `Map>` | O(n) expected (R07.11.3) | | `s.tally(by: k)` | `Counter` | O(n) expected (R07.11.4) | | `compress(s)` | `(domain C, comp)`: values sorted and deduped, as a fresh domain | O(n log n) (R07.11.5) | Sorts are stable. Descending is a key, not a flag: `by: x => desc(x.score)`. Every in-place verb that has a result-named twin follows the same pattern (`sort`/`sorted`, `dedup`/`deduped`); `.rev` (view) and `reverse()` (in place) are different jobs, not twins. ## More vocabulary | Form | Meaning | Cost | |---|---|---| | `s.drop_while(p)` | skip the leading elements where `p` holds, yield the rest | O(1) per step (R07.12.1) | | `s.flat_map(f)`, `s.flatten()` | each element to a sequence, all inner elements in order | O(1) per element (R07.12.2) | | `iterate(x, step)` | `x, step(x), step(step(x)), ...` until `step` gives `None` | O(1) per step (R07.12.3) | | `s.is_sorted(by:)`, `s.is_subsequence(t)` | the two common checks | O(n) (R07.12.4) | | `a.partition_point(ok)`, `a.equal_range(x, by:)` | on sorted `a`: the cut where monotone `ok` turns true; the range equal to `x` | O(log n) (R07.12.5) | | `a.next_permutation()`, `a.prev_permutation()` | step to the neighbouring arrangement in place; `false` past the end | amortized O(1) (R07.12.6) | | `a.rotate_left(k)`, `a.rotate_right(k)`; `s.rotated_left(k)`, `s.rotated_right(k)` | rotate in place; a rotated copy | O(n) (R07.12.7) | | `m.get_or_insert(k, v)` | `m[k]`, storing `v` first if absent: `ids.get_or_insert(name, ids.len)` | O(log n) (R07.12.8) | ## Answers to round 2's questions 1. **In-place vs copy:** both, by rule: a verb mutates, its result-named twin allocates. 2. **Folds on possibly-empty input:** `NonEmpty` is gone. Identity-backed folds (`sum`, `fold(+)`) are plain `T`; `min`/`max` are `?T` and you write `a.max()!` when you know. 3. **`scan`:** n + 1 values indexed by cuts; suffix folds come from `.rev`. ## Open None. Indexed sequences use `.keys` and domains `V.range`; `.collect()` keeps its name (decision 186). ## What goes away `View`, `view()`, 0-based `.at(i)` / `.try_at(i)` on `Indexed`, `drop_first` (now `drop`), `skip`, `step_by`, `first_at`, `order`, `chunk_by`, `run_ranges`, `excl_fold`, `suffix_scan`, `scan_in_place`. Each is a view, a fold over `.keys`, or `.rev.scan`. --- # 8. Traits, generics, laws and row types URL: /docs/ref/core/08-traits-generics This is the normative specification ([source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/core/08-traits-generics.md)). For a gentler introduction, start with the [guides](/docs/guides). Status: draft for 0.3.0. Sources: archived `design/spec/14`; decisions 59, 116, 127, 142, 146 (row types, trial), round 5 (`lib/ops-ranges.md`) for laws; `12-powers.md` for what user libraries can define. ## 8.1 Traits and impls ``` trait Ord(Eq): fn cmp(self, other: Self) -> Ordering trait Next: type Arc: Target fn next(self, v: V) -> yields Arc trait Monoid(Op): fn id(self) -> T law left_id(x: T) = self.op(self.id, x) == x impl Ord for Frac: fn cmp(self, o: Frac) -> Ordering = (self.p * o.q).cmp(o.p * self.q) ``` - A trait declares methods (with optional default bodies), associated types, field requirements and laws. Supertraits go in parentheses. (R08.1.1) - `impl Trait for T` implements it; `impl A + B for T` is shorthand for two impls. One impl per (trait, type), declared with the trait or the type. Blanket impls are allowed (`impl Add for ?T`). (R08.1.2) - Inherent methods (`impl T:` or methods in a struct body) live in the type's module only. (R08.1.3) - Method lookup: inherent first, then traits in scope that the type implements; two candidates at one step is an ambiguity error naming both, resolved by `Trait.m(x, ...)`. No auto-ref or auto-deref. (R08.1.4) - Operators are trait methods (`Add`, `Sub`, `Mul`, `Div`, `Rem` with `Rhs` and `Out`, `Neg`, `BitAnd`, ..., `Index`, `Ord`, `Eq`, `Hash`, `Print`, `Read`, `Unwrap`). Compound assignment comes from the operator. (R08.1.5) - **Derived impls are structural**: tuples, records, structs and enums get `Eq`, `Ord` (lexicographic in declaration order, variants in declaration order), `Hash`, `Print` and `Read` when every field has them, unless the type writes its own impl. Tuples and records (not structs, whose fields may be private) also get `+`, `-` and `Zero` fieldwise when every field has them, so a rerooting DP over `(cnt: Int, sum: Int)` passes `+` as its operation. (R08.1.6) - **Field traits**: a trait may require fields (`trait Target: to: V`). Records satisfy field-only traits structurally; named structs opt in with a bodiless `impl Target for Edge`. (R08.1.7) - Library-authored diagnostics: a trait may attach a message to "not implemented" and to each law, so `SegTree(f, a)` with a non-associative `f` says what to write. (R08.1.8) `cmp(a, b)` is the three-way comparison of two `Ord` values, an `Ordering` (`Less`, `Equal`, `Greater`); `desc(x)` flips an order. ## 8.2 Generics ``` fn argmax(s: S, by: S.Item -> K = id) -> ?S.Key fn dijkstra(g: WeightedNext, from: Seq<(V, W)>) -> Paths fn f(a: [I, J]Int) struct Pair: a: A, b: B ``` - Bounds go inline (`T: Ord + Hash`), in a `where` clause, or directly as a parameter type: `g: WeightedNext` means "some type implementing it" (decision 146). (R08.2.1) - Generic bodies are checked once against their bounds, at definition; errors point at the generic or the call, never inside an instantiation. (R08.2.2) - Everything is monomorphized; there are no vtables and no `dyn`. (R08.2.3) - `domain` is a kind on type parameters; `const N: Int` parameters take compile-time values (`Mod<998244353>`, `SegTree<0..=4e9>`); range types are types and may be arguments. (R08.2.4) - Type-parameter defaults fill omitted trailing arguments. (R08.2.5) - **Trait aliases** name a bundle of bounds: `trait WeightedNext = Next where Arc: Target + Weighted`. (R08.2.6) - **Associated types** are reached through the implementing type or a value: `S.Item`, `g.Arc`. (R08.2.7) - Return-type dispatch: a call may be resolved by its expected type (`read()`). (R08.2.8) - **Conditional code** on a bound: `if T: Commutative: ... else: ...` chooses at compile time; it is how laws select a specialization (`lib/ops-ranges.md`). `if const cond:` branches on a compile-time value. (R08.2.9) ## 8.3 Laws ``` trait Op: fn op(self, a: T, b: T) -> T law assoc(a: T, b: T, c: T) = self.op(self.op(a, b), c) == self.op(a, self.op(b, c)) trait Commutative(Op): law comm(a: T, b: T) = self.op(a, b) == self.op(b, a) ``` - A `law` is a Boolean property of a trait's operations. Implementing a trait promises its laws (trust tier "promised", chapter 9). (R08.3.1) - Laws are never assumed by the type checker. They select documented, answer-preserving specializations (a segment tree without push-down when tags commute), and `cpl explain` names each selection. (R08.3.2) - `cpl stress` samples laws on the values a program actually builds; `laws_hold(op, samples)` checks them directly; `--laws=off` skips. (R08.3.3) - A false law gives wrong answers, never undefined behaviour. (R08.3.4) ## 8.4 Record row types (trial) ``` fn undirected(n: V.count, edges: Seq) -> Graph let a2 = (..a, to: u) // record update ``` - `(f: T, ..)` is a bound: any record with at least those fields, in any order. `R` names the whole record; `..R without (u, v)` is its other fields as a record. (R08.4.1) - There is no subtyping: a record with more fields is not usable where fewer are expected unless the parameter is written with a row bound. Dropping fields is explicit (`keep:` on graphs, `without` in types). (R08.4.2) - Row-polymorphic functions are monomorphized per record type. (R08.4.3) - Nine safety rules (decision 146): no hidden heap copies, no field reordering visible to the program, row variables only on records, duplicate fields an error, `without` of a missing field an error, rows not inferred across statements, no rows on named structs, field access through a row is O(1), and rows never change layout of an existing value. (R08.4.4) ## 8.5 What is deliberately missing - No inheritance, subclassing or default-method overriding chains. (R08.5.1) - No overloading by type, no implicit conversions, no orphan impls. (R08.5.2) - No higher-kinded types; capability traits on sequences (`07-sequences.md`) and associated types cover the stdlib's needs. (R08.5.3) - No user-defined patterns (decision 132) and no macros. (R08.5.4) --- # 9. Contexts, checks and build modes URL: /docs/ref/core/09-contexts-checks This is the normative specification ([source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/core/09-contexts-checks.md)). For a gentler introduction, start with the [guides](/docs/guides). Status: draft for 0.3.0. Sources: archived `design/spec/17-contexts.md`, `18-checks-lowering.md`; decisions 100, 145, 148. Decision 148 supersedes the older rule that unproven checks stay in submissions. ## 9.1 Contexts A context is a library-declared record of compile-time values with defaults. It replaces a flag per feature with one mechanism: ``` context io: base: 0 | 1 = 0 sep: Str = " " answers: (Str, Str) = profile.answers precision: ?Int = profile.precision ``` Any block sets one: ``` with io(base: 1) // bare line at the top of a block: the rest of it with checks(bounds: off): // block form for x in A: ... read(base: 0) // a call argument beats every context ``` - Precedence: call argument, then the innermost `with`, then outer ones, then the default. A bare `with` line must come first in its block (the formatter enforces it). (R09.1.1) - Values are compile-time constants. A runtime value is a parameter or a fresh type (`type Z = Mod(p)`), never a context: a table built under one modulus must not be read under another. (R09.1.2) - Contexts are **lexical**: a body sees the contexts where it is written. A function that should follow its caller declares `uses ctx`; the caller's value is then an implicit compile-time argument, passed on to further `uses` callees. `uses` is inferred only for nested fns and lambdas; public fns, trait methods and modules declare it. (R09.1.3) - Cost: one specialized copy of each `uses` function per distinct value; `cpl explain` lists them and the bundle-size warning counts them. (R09.1.4) - Standard contexts: `io` (chapter 10), `checks` (below), `lint` (one field per lint: `with lint(float_eq: allow)`), `stress` (default sizes, time budget). User libraries declare their own. (R09.1.5) ## 9.2 Build modes | Mode | Used by | Checks | |---|---|---| | checked | `cpl run`, `cpl stress`, `cpl test`, the interpreter, `cpl build --checked`, C++ with `-DLOCAL` | every unproven check traps (R09.2.1) | | release | `cpl build`, `cpl submit`, the bundle on the judge | no runtime checks unless opted in (R09.2.2) | **The rule for every check** (decision 148): on the judge only valid programs matter, so release optimizes for them. Valid programs behave identically in both modes and in the interpreter, and the lowering never adds undefined behaviour to a valid program. A program that would trap in a checked build is invalid, and in release it gets whatever its C++ does: usually a wrong answer, possibly a crash or C++ undefined behaviour (an unchecked index past the end reads out of bounds), the same as the hand-written C++ it replaces. Where avoiding UB is free the lowering still does it (wrapping arithmetic through unsigned casts, masked shifts, no uninitialized reads), so `-O2` cannot miscompile the valid code around a bug; it never adds a branch or a clamp to do so. To keep a check on the judge, opt in (§9.4). **Checks never call user code.** A checked build makes exactly the calls to user functions, closures and input that release makes, in the same order: a check may only inspect values the program already computed. So an interactive query, a counter in a closure or a `@cache` sees the same history in both modes. (R09.2.3) ## 9.3 What is checked Every checked operation answers three questions: what it means, what the compiler can prove, and what each build does. | Check | Proved away when | Checked build | Release | |---|---|---|---| | index `a[i]` with `i: D` on `[D]T` | always (the type is the proof) | none | none (R09.3.1) | | `D(x)` from an `Int`, raw index, `List` index | range facts show it fits | trap with value and bounds | unchecked (R09.3.2) | | store into a range type | the value's range fits (`x % 7` into `0..7`) | trap naming value and range | truncates to the width (R09.3.3) | | `Int` / `I128` overflow | interval arithmetic proves it fits | trap with operands | wraps (R09.3.4) | | `x!` on `None` | flow proves `Some` | trap naming the place | reads the niche as a value (R09.3.5) | | division by zero, negative shift, `sqrt` of a negative | the divisor's range excludes 0 | trap | defined fallback (0) (R09.3.6) | | `assert c` | n/a | trap with the message | skipped (R09.3.7) | | `@cache` cold-mode check | n/a | stress compares cold and cached runs | none (R09.3.8) | | `law` promises | n/a | stress samples them | none (R09.3.9) | Each row has one check name, used by `with checks(...)`, `release_checks:` and diagnostics: `bounds` (the first two rows), `ranges`, `overflow`, `unwrap`, `div`, `asserts`, and `reads` below. `@cache` and laws are stress-only and have no name. This is the one list; other chapters link here. Reads (`read<1..=n>()`) are input validation: they are checked in checked builds and, like other checks, skipped in release unless `release_checks: [reads]` is set. ## 9.4 Turning checks on and off ``` with checks(ranges: on, overflow: on, bounds: on): // also in release ... with checks(overflow: off): // also in checked builds ... unchecked: // every check off, every build ... ``` - `with checks(...: on)` keeps those checks in release for a block or file. A judge profile can keep them for a whole submission with `release_checks: [ranges, overflow]`. (R09.4.1) - `with checks(...: off)` removes a check in checked builds too, for a hot loop whose stress runs are too slow. (R09.4.2) - `unchecked:` is the greppable escape: a statement block with every check off in every build. (R09.4.3) - Lints are contexts: `with lint(name: allow)` silences one in a scope. Lints are declared by the library that owns the names they mention; the linter has no hard-coded stdlib names. (R09.4.4) ## 9.5 Trust tiers Every fact the compiler relies on is in one tier (`05-ownership.md`): 1. **proved**: the type checker, range analysis or borrow rules establish it; no runtime cost. (R09.5.1) 2. **trapped**: not proved; checked builds trap, release assumes it. (R09.5.2) 3. **promised**: the author states it and tooling samples it: `law` declarations, `@cache` correctness. Codegen never optimizes on a promise alone beyond the documented specialization it selects; a false promise gives a wrong answer, never undefined behaviour. (R09.5.3) 4. **unsafe**: `@trusted:` blocks and `@cpp` inline C++. These are the only places a contestant can write undefined behaviour, and `cpl explain` lists every site. (R09.5.4) ## 9.6 Recursion and the stack The bundle runs `main` on a thread whose stack comes from the judge profile (default 1 GB). There is no depth inference or counting; a stack overflow crashes as in C++, and the checked runtime prints the call trace. Runtime-sized arrays and static arrays over 4 KB never go on the stack. --- # 10. Input, output and program shape URL: /docs/ref/core/10-io This is the normative specification ([source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/core/10-io.md)). For a gentler introduction, start with the [guides](/docs/guides). Status: draft for 0.3.0. Sources: archived `design/spec/25-io.md`, `31-interaction.md`, `32-graders-bundling.md`; decisions 20, 136, 139. Nothing here is compiler-special except return-type dispatch: I/O is byte intrinsics, two traits, and the `io` context. ## 10.1 Program shape A program is a flat sequence of top-level statements run top to bottom; there is no required `main` or `solve`. ``` let sv = Sieve(1e6) // runs once @!multitest let n: 1..=2e5 = read() // runs once per test case let a = read<[n]Int>() print(a.sum()) ``` - `@!multitest` reads the test count and runs everything below it per case; `@!multitest(until_eof)` runs until input ends. State declared below the divider is per-test, and a fresh type declared below it can not leak into the next case (chapter 2). (R10.1.1) - Top-level `return` ends the program, or the current case under `@!multitest`. (R10.1.2) - IOI-style tasks mark entry points with `@grader`, `@grader(interactive)` or `@grader(two_phase)` on a `fn` or `mod`, and declare judge-provided functions with `extern fn`. The judge profile supplies the harness; local runs use a generated stub (decision 136). (R10.1.3) ## 10.2 Reading ``` trait Read: fn read() -> Self uses io fn read() -> T ``` - `read()` dispatches on the expected type, so `let n: 1..=2e5 = read()` and `read<[n]Int>()` are the same mechanism. (R10.2.1) - Range types read with their contract. A domain written with explicit ends (`1..=n`, `0..n`, `lo..=hi`) reads and prints its positions as their integers, never shifted. `io.base` applies only to *counted* domains, declared by a count alone (`[n]T`, or `domain E = [m]`, where `[m]` in a domain declaration is shorthand for `0..m`): `with io(base: 1)` makes 1-based input for them 0-based positions, and back on output. So the two never stack. Sizes, cuts and plain integers never convert. (R10.2.2) - Arrays `[D]T` read `D.count` values; `[R, C]Char` reads rows of characters with no separators; `[V]List` reads count-prefixed rows; `[Pair]T` reads a lower triangle without its diagonal (row `i` gives the values for every earlier `j`), since it walks in that order; records, tuples and structs read their fields in order; an enum reads one token, picks the variant whose tag (or name) it equals (an integer `@tag(1)` compares as a number, so `01` matches), then reads that variant's fields, so a command stream is `read()` in a loop; `Range` reads two ends `l r` as the inclusive `l..=r`, the statements' convention, and checks `l <= r`; `Bool` is not a token type (`read()` is E0315), and `yes(b)` prints `io.answers`, `("YES", "NO")` in the default profile; `Str` reads one token; `read_line()` reads the rest of the line; `Char` skips whitespace then reads one character. `Mod

` reads one signed integer token of any length and reduces it modulo `P`, so a 10^4-digit coefficient is `read>()`. (R10.2.3) - `s.parse()` reads a `T` from a string by these same rules, `None` on a bad or leftover token: one token read under two moduli is `let s = read()` then `s.parse>()!` and `s.parse>()!`. (R10.2.4) - Graphs are built from an edge list read as records, `read<[E](u: V, v: V)>()`, then `Graph.undirected(edges)` or `.directed` (`lib/graphs-trees.md`); there is no `Graph.read`. (R10.2.5) - A bad token traps with the input position and the expected type. (R10.2.6) - `read_all()` reads every remaining `T` until the input ends, for statements that give no count; reading after it is an error. O(tokens). `read_all(until: f)` stops at the first value with `f` true, a sentinel, which it consumes and leaves out; reading may continue after it (decision 161). (R10.2.7) ## 10.3 Printing - `print(x, y, ...)` joins by `io.sep` and ends the line; `print(xs)` prints a sequence on one line; `print(xs, sep: "\n")` overrides; `print(xs, none: -1)` prints each absent element of a `?T` sequence as `-1`. (R10.3.1) - Interpolated strings format each piece through `Print`; positions print in the file's base; `"{x:.9}"` sets float precision. (R10.3.2) - `Bool` is not `Print`: `print(b)` is an error naming `print(yes(b))`. `yes(b)` is the word from `io.answers`, a `Str`, so it also works in interpolation (`yes(b, answers: ("Possible", "Impossible"))`). (R10.3.3) - `F64` uses `io.precision` or `print(x, precision: k)`. (R10.3.4) - Derived structurally (see R08.1.6), with nothing to write: records, tuples and structs print their fields joined by `io.sep`; enums print their variant name unless the type implements `Print`. (R10.3.5) - Output mirrors input, shape for shape, except that counts are never written for you. `[R, C]Char` prints one row per line with no separators. Any other `[R, C]T`, a `[V]List` and a `List>` print one inner row per line, joined by `io.sep`. `[Pair]T` prints its lower triangle row by row. To print a count-prefixed row, print the count: `print(xs.len, xs)` prints the length and the elements on one line. (R10.3.6) ## 10.4 Interaction `Wire` switches to interactive mode: every read and every exit flushes first. A query is `wire.ask("? {x} {y}")`: print a line, flush, and read the answer as the type the call site expects (`fn ask(x: Int, y: Int) -> Int = wire.ask("? {x} {y}")`). A program that never constructs one never flushes early. A trap in any mode flushes buffered output before writing to stderr. The local interactor harness (`cpl interact`, `tools/stress.md`) runs the program against an `@interactor` fn or an external binary. ## 10.5 Signatures `read` and `print` are core, so they have no stub in `spec/std`. Their exact forms: ```text fn read(base: Int = io.base) -> T fn read_line() -> Str fn read_all(until: ?(T -> Bool) = None) -> List // std.io fn print(xs: Print..., sep: Str = io.sep, end: Str = "\n", none: ?Print = None, precision: ?Int = io.precision) fn yes(ok: Bool, answers: ?(Str, Str) = None) -> Str // std.io ``` `print` takes any number of positional values. A sequence argument prints its elements joined by `sep`. `none:` replaces each absent element of a `?T` sequence. `?T` is not `Print`, like `Bool`, so printing one without `none:` is a compile error that names it. `end: ""` leaves the line open. ## 10.6 Cost Input is one bulk read and a hand-rolled parser; output is one buffer written at exit (or per flush in interactive mode). `io` is a compile-time context, so `- io.base` folds away. --- # 11. Files, modules, prelude and versions URL: /docs/ref/core/11-modules-prelude This is the normative specification ([source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/core/11-modules-prelude.md)). For a gentler introduction, start with the [guides](/docs/guides). Status: draft for 0.3.0. Sources: `plan/15-program-structure.md` §2, §12-14; decisions 72, 94; `spec/std/prelude.cp`. ## 11.1 Program files and library files - A **program** file is a sequence of statements (chapter 10). It may declare items anywhere; items hoist within their block. (R11.1.1) - A **library** file contains only items (`fn`, `struct`, `enum`, `trait`, `impl`, `type`, `const`, `domain` with a constant count, `context`, `marker`) and `use` lines. `pub` marks exports; everything else is private to the file. (R11.1.2) - An inline module `mod name:` groups items inside any file, for parts a contestant wants to stress alone or a grader entry (`@grader mod`). (R11.1.3) ## 11.2 `use` ``` use std.segtree // the stdlib: `segtree.SegTree` use std.graph.{dijkstra, Paths} use lib.treap // the contestant's library root, from cp.toml use lib.flow as fl ``` - Paths are module names, not files on a search path: `std` is the pinned stdlib, `lib` is the roots named in `cp.toml`. (R11.2.1) - Modules form an acyclic graph; two modules that need each other are one module. (R11.2.2) - A local name shadows a prelude name; a `use` that collides with a local name is an error naming both. (R11.2.3) - Everything is inlined into the one output file and tree-shaken: only called functions and used generic instances cost bytes (`tools/bundle.md`). Library code is specialized where it is used, so it is as fast as code in the file. (R11.2.4) ## 11.3 The prelude The prelude is the set of library names every program sees without a `use`. It is one ordinary file, `std/prelude.cp`, made of `use` lines, so what each name means is in its own module; the compiler has no built-in list. Rules: - Only programs get the prelude; library modules `use` what they need, so a library never depends on what a program happened to import. (R11.3.1) - The prelude is the vocabulary of the `lib/` chapters, by rule rather than by request (decision 150): every pub type and free function in a chapter's main tables is in it, and nothing else is. `std/prelude.cp` is the authoritative list; `scripts/spec-stub.py` checks it against the tables. Adding an API to a chapter's table adds it to the prelude; a helper the tables don't list needs a `use`. There is no name budget: the cost of a prelude name is a collision, not a count. (R11.3.2) - Two exclusions keep that safe. A name a contestant commonly gives a local (`n`, `a`, `g`, `dp`, `ans`, `cnt`, `left`, `best`) is never a prelude name; the library spells it otherwise. And a name with two plausible meanings across chapters gets one chapter's meaning and the others are qualified (`min` and `max` stay the binary builtins; the folds are methods). (R11.3.3) - `scripts/spec-stub.py --check` keeps `std/prelude.cp` and the chapter tables in step. The groups are: core types and traits; sequence vocabulary (`07-sequences.md`, `lib/sequence-patterns.md`); search and DP; graphs and trees; operations and range structures; containers; math and `Mod`; strings; I/O. - The LSP offers an import quick fix for any non-prelude stdlib name, and `cpl fmt` sorts `use` lines. (R11.3.5) ## 11.4 Versions, pins and migration - The first line of a solution is a compiler stamp, added by the formatter: `// cpl 0.3.0`. The generated C++ carries the stamp and a source hash. (R11.4.1) - `cp.toml` pins the stdlib and each library root by content hash. Old solutions rebuild byte for byte with their pinned compiler and libraries (`cpl build --compiler 0.3.0`). (R11.4.2) - A breaking stdlib change ships a codemod: `cpl migrate` rewrites solutions and personal libraries, shows the diff, and records the new pin. Renames keep a deprecated alias for one minor version, with a diagnostic naming the new spelling. (R11.4.3) ## 11.5 What the submission contains `cpl submit` produces one C++17 file with the program as `main` (or the grader entry points), the library code it reaches, and the stamp. It drops tests, brutes, generators, checkers, interactors, samples, `debug(...)` calls and `@local` items. --- # Powers: what a user library can define URL: /docs/ref/core/12-powers This is the normative specification ([source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/core/12-powers.md)). For a gentler introduction, start with the [guides](/docs/guides). A power is a mechanism that lets library code feel built in. The stdlib has no power a user library lacks: if a stub in `spec/std/` needs something, it is listed here, or it is core syntax in `delta/parser-gaps.md`. A power earns its place by the stdlib families it unlocks; one family means look for another design. Each entry: the decision, the smallest example, what needs it, and whether `scripts/spec-check.sh` already accepts it (**checks**), accepts part of it (**partial**) or not yet (**no**). Lowering for every power is monomorphized, inlined C++; any `std::function` or hidden allocation is logged debt. ## W1. Numeric types (P1) A type becomes a number by defining operators, `Int` literal conversion and `read`/`print`. Compound assignments (`+=`, `min=`) come from the operators. struct Frac: p: Int, q: Int impl Num for Frac: fn from_int(n: Int) -> Frac = Frac(n, 1) fn (a: Frac) + (b: Frac) -> Frac = norm(a.p * b.q + b.p * a.q, a.q * b.q) fn (a: Frac) * (b: Frac) -> Frac = norm(a.p * b.p, a.q * b.q) let half: Frac = 1 / 2 // literals convert through from_int Range facts (what the overflow checker may assume about a result) are declared on the return type: `fn (a: Mod

) + (b: Mod

) -> 0..P`. Needs: `Mod

`, `Frac`, `Matrix`, `Poly`, `Point`, `I128`. Status: partial (operators check; literal conversion through `from_int` does not). ## W2. Niches (P2) `?T` costs no space when `T` has an unused value. Ints, domains, ranges, references and enums have one; a struct has one when any field has one, and `?S` uses the first such field. Automatic, never worse (it majorizes), shown by `cpl explain`. No syntax. Needs: every optional record (`?Edge`, `?Pair`), `[V]?Int` distance arrays. Status: checks (layout is codegen debt). ## W3. Reflection and derives (P3) Every struct and enum gets, by field order: `==`, `<` (lexicographic), hash, `print`, `read`, and, when every field is a finite index, an index domain (decision 2.16). A library derives more with a compile-time loop over fields: pub fn show(x: T) -> Str = ", ".join(for f in T.fields: f"{f.name}={x.(f)}") `T.fields`, `T.variants` and `x.(f)` are resolved at compile time, so the loop unrolls. Needs: sorting records, hashing tuples, `[Sign]Path`, trace printing. Status: partial (built-in derives check; `T.fields` does not). ## W4. Sequences, views and index spaces (P4) One iteration protocol: anything with `iter` (a generator) is a `Seq` and works in `for`, comprehensions and every sequence method. Five more capabilities layer on it; each operation asks for the weakest one that keeps it at its stated cost (decision 142): pub trait Seq: fn iter(self) -> yields T // walk in order pub trait Keyed: Seq: fn items(self) -> yields (K, T) // each element knows its key pub trait Sized: len: Int // O(1) length pub trait Bidir: Seq: fn iter_rev(self) -> yields T // walk backwards pub trait Indexed: Keyed, Sized, Bidir: fn at(self, k: K) -> T // O(1) s[k] keys: Range // contiguous keys pub trait IndexedMut: Indexed: fn at(mut self, k: K) -> lends mut T // s[k] is a place pub trait Contains: fn contains(self, x: T) -> Bool // `x in s`, sub-linear only | Needs | Operations | |---|---| | `Seq` | `map`, `filter`, `take_while`, `chain`, folds, `min`/`max`, `any`/`all`, `first(p)`, `tally`, `runs`, `pairs`, `keyed()`, `collect()`, `sorted()` (R12.4.1) | | `Keyed` | `.items`, `find`, `find_all`, `argmax`/`argmin`: walk and remember keys (R12.4.2) | | `Sized` | `.len` (R12.4.3) | | `Bidir` | `.rev`, `.last` as an O(1) property (R12.4.4) | | `Indexed` | `s[k]`, slices, `nth`, `bsearch`, `first_ge`, string algorithms, `zip` (R12.4.5) | | `IndexedMut` | `sort()`, `reverse()`, `swap`, `select`, `shuffle`, `next_perm`, slice assignment (R12.4.6) | | `Contains` | `x in s`: sets, maps (keys), bitsets, ranges; a linear search is `s.any(x)` (R12.4.7) | `at(k)` takes a key, the same key as `s[k]`; it is never a walk offset. On `w = s[2..]`, `w.at(2)` is `s[2]` and `w.at(0)` traps. Walking by position is `nth(k)`, which is `s.at(s.keys.nth(k))`, so generic code that counts from 0 over any `Indexed` (`zip`, `select`, `next_permutation`) reads with `nth` (see R04b.1.4). (R12.4.13) Generators are `Seq` only: a yield number is not an identity, so `dfs(s).argmax()` is an error suggesting `.keyed(by: v => v)` or `.max()`. `s.keyed(keys)` makes any `Seq` `Keyed`, pairing by walk order (`keys` defaults to `0..`, a counter); `s.keyed(by: f)` takes each key from its value. There is no `enumerate`: `for (i, x) in g.keyed().items` (decision 60). Sortedness is a precondition checked in debug builds, not a trait. `Map` is `Keyed`, `Sized` and `Contains` with its own `[]`; there is no `Lookup` trait. Every value is owned or lent (read or `mut`); the mode is not part of the type. Five rules, with no lifetime annotations (decisions 141, 144; the full model with exercises is `spec/core/05-ownership.md`): 1. Parameters are lent: a fn never owns its arguments. (R12.4.8) 2. A value is lent if any part is: a struct's fields, a closure's captures, a generator value's arguments. It is `mut`-lent if any part is, and it borrows every source its parts borrow. (R12.4.9) 3. A lent value lives until its last use. It may be kept in a `let`, `var`, field or container that dies no later than its sources (same or inner block, declared after them); never returned except by a fn declared `lends`, stored through a parameter, or stored in a top-level `var`. (R12.4.10) 4. While it lives its sources are lent: a read lend forbids writing, resizing or moving them, and a `mut` lend excludes every other access. A closure's captures are borrowed per call, not for its life. (R12.4.11) 5. Owned values move: `let b = a` and `S(a)` move `a`; `a.clone()` copies. (R12.4.12) A view is a `Seq` (and `Indexed` when reads stay O(1)) built from a lent source. There is no `View` trait and no marker on the struct: the same `Filter` owns its source when built from an owned value (`Filter(xs, p)` moves `xs`) and borrows it when built from a lent one (`arr.filter(p)`, since `self` is lent). A fn that returns a lent value says so in its signature; by default the result borrows every lent parameter that is not a plain value (`Int`, `Bool`, ranges, positions), and `lends(xs)` narrows it. The body is checked against the signature, so call sites and `= todo` stubs need nothing more: pub struct Filter: src: S keep: P // the closure's own type: no boxing impl Seq for Filter, P: T -> Bool>: fn iter(self) -> yields T = for x in self.src: if self.keep(x): yield x impl Keyed for Filter, P: T -> Bool>: fn items(self) -> yields (K, T) = // keys survive filtering for (k, x) in self.src.items(): if self.keep(x): yield (k, x) impl Bidir for Filter, P: T -> Bool>: fn iter_rev(self) -> yields T = for x in self.src.rev: if self.keep(x): yield x pub fn filter, T, P: T -> Bool>(self: S, keep: P) -> lends Filter = Filter(self, keep) fn window(xs: [V]Int, r: Range) -> lends [V]Int = xs[r] pub fn at(mut self, i: D) -> lends mut T // a writable place: the same keyword A `for` over a generator pastes its body at the loop and each `yield x` becomes the loop body, so `for y in a.filter(p).map(f): b(y)` is `for x in a: if p(x): b(f(x))`, and `break`, `continue` and `return` act on that one loop. An adapter implements each capability it can keep O(1): `Filter` keeps `Keyed` and `Bidir` but not `Sized` or `Indexed`, so `a.filter(p).argmax()` walks `a.items()` once and answers with a key of `a`. Recursive generators pass the body as a closure that returns continue or stop. `Slice`, `Rev`, `Map`, `Filter`, `TakeWhile` and `Chain` are each a few lines like this, with no stdlib privilege. An index space is a domain: a declared or fresh finite type with `D.count`, `D.cuts` (its cuts) and `D.at(i)`. Generic code takes `D: Domain` and stores `[D]T`; runtime-sized domains read their declaration-site slot (decision 124 and the summary in `decisions.md`). pub struct Fenwick: tree: [D]T pub fn fold(self, r: Range) -> T = ... // a cut range converts here Needs: every container, `SegTree`, `Fenwick`, `Graph`, `t.Pre`, `SortedSet.range`, `Window`. Status: partial (domains and `[D]T` check; `Seq` is informal, so some sequence methods exist only on `List`). ## W5. Patterns (P5): closed Values destructure by their stored shape only. A view is a method returning an enum: `match t.node(v): Leaf => ... Inner(l, r) => ...`. Decision 132, with its reopening condition. Status: checks. ## W6. Generators and steering (P6) `fn f(...) -> yields T` is a generator; `yield` produces, plain `return` ends. A `for` over it supports `break`, labelled `break`, `return` and loop `else`, including through recursive generators (decision 126). The item type may carry methods that talk back to the generator; it checks a flag on its own item after each `yield`: pub enum Visit: Enter(v: V, via: ?A), Exit(v: V, via: ?A), Again(from: V, via: A) pub fn dfs>(g: G, from: Seq, seen: ?mut [V]Bool = None) -> yields Visit // step.prune() after Enter Closures passed to a library are guaranteed to inline when they do not escape (fn parameters of non-recursive generics). Non-local `return` from a closure is deferred until ports need it. Lockstep over two recursive generators: materialize with `List(g)`. Needs: `bfs`, `dfs`, `t.Pre`, `submasks`, `divisors`, `reach`, every search. Status: partial (generators and `break` check and run; item steering and recursive-generator `return` are implementation debt). ## W7. Functions as values (P7) Operators and named functions are values: `SegTree(+)`, `keep: max`, `by: <`, `xs.sort(by: p => p.x)`. Named and default arguments work in user functions exactly as in the stdlib; options are named arguments, never `_by` variants. Recursive `let` lambdas lower to a self-passing generic lambda (decision 127). No overloading: a function is its name plus its labels. Status: partial (operator values and defaults check; recursive `let` lambdas do not parse yet). ## W8. User places (P8) A type defines what `x[k]` is as a place with one of two protocols: pub trait IndexMut: fn at_mut(mut self, k: K) -> mut T // a real place pub trait IndexSet: fn set(mut self, k: K, v: T) // write-through With `at_mut`, `mut x[k]`, `let p = mut x[k]` and `x[k] op= v` are ordinary places. With only `set`, `x[k] = v` calls `set` and `x[k] op= v` is `set(k, at(k) op v)`, with `k` evaluated once; a named alias is an error pointing at the method. `SegTree` uses `set` (an update must recompute ancestors); `Map` uses `at_mut` and inserts the default (decision 128). Moves: returning any value is O(1); `.take()` moves out of a place that stays live; parameters are lends, `mut` lends allow draining (`a.absorb(mut b)`). Overlapping `mut` places are a compile error. Needs: `SegTree`, `Fenwick`, `Map`, `Counter`, small-to-large. Status: partial (`Map` places check; `IndexSet` desugaring does not). ## W9. Operators on user types (P9) One spelling: `fn (a: T) op (b: T) -> R` defines `op`, unary `fn -(a: T)`, comparison `fn (a: T) < (b: T) -> Bool` (or the derived order). It is the `Add`/`Mul`/... protocol impl written the way the operator reads, so generic code bounded by `T: Add` accepts it. `impl Add for T` is no longer written by hand (decision 133). Status: partial (`impl Add for` checks; the `fn (a) + (b)` spelling does not parse yet). ## W10. Protocols, laws and operation values (P10) Traits have `Self`, associated types and constants, and may state laws that `laws_hold` tests and `cpl stress` samples: pub trait Add: fn (a: Self) + (b: Self) -> Self law assoc(a, b, c) = (a + b) + c == a + (b + c) Algebra stays operation values (decision 3.1): a structure takes a binary fn (`SegTree(+)`, `SparseTable(min)`, `scan(xs, gcd)`). Its identity comes from the element type: `+` uses `T.zero`, `*` uses `T.one`, `min`/`max` over `?T` use `None`; a user type supplies them as constants (`const zero = Low(...)`). Anything else passes `id:`: `SegTree(op: f, id: e)`. A missing identity is an error naming the constant to define. Lazy propagation takes an action value `act: (f, x) => ...` with `compose:`. Const generics: `Mod

`, `[n]T`, `Bitset`. Needs: `SegTree`, `LazySegTree`, `SparseTable`, `Fenwick`, `Matrix`, scans, ordered containers (`Ord`), hashing (`Hash`). Status: partial (traits check; laws, `T.zero` identities and `Self` at run time do not). ## W10a. Records, associated types and inline bounds (P10) Graphs (decision 146) need five mechanisms; each is open to user code. - **Associated types.** A trait names a type its implementor picks, read as `Self.Arc` or `G.Arc`: pub trait Next: type Arc: Target fn out(self, u: V) -> yields Self.Arc - **Trait aliases.** `pub trait WeightedNext = Next where Self.Arc: Weighted` names a bound; it has no members and no impls. (R12.11.1) - **Inline bounds.** A trait in a parameter's type is a fresh hidden type parameter, static per caller, like `P: T -> Bool` for fns: `fn dijkstra(g: WeightedNext, from: Seq<(V, W)>)`. Name it (`>(g: G)`) when a return type or a second parameter mentions it. (R12.11.2) - **Field traits.** A trait whose members are all `@get` is satisfied by any record with fields of those names and types: `(to: V, w: Int)` is a `Target + Weighted`. A named struct opts in with a bodiless `impl Weighted for Road`. (R12.11.3) - **Row bounds and record update.** `R: (u: V, v: V, ..)` bounds a type parameter to records with at least those fields; `(to: V, ..R without (u, v))` is R's other fields after new ones, in R's order; `(..a, to: u)` is `a` with `to` replaced (heap fields move). No record subtyping: rows only bound type parameters, matched by monomorphization. A generic body sees only the named fields. (R12.11.4) Needs: `Graph.directed`/`undirected` over any edge record, `keep:`, `transpose`, every graph algorithm's signature, `.weighted(f)`. Status: no (stubs load in spec mode; outside it the parser rejects row bounds and `without` with E0108, record update E0102, aliases E0103, and an inline bound is E0204). ## W11. Reading and printing (P11) `read()` and `print(x)` go through `Read` and `Print`, derived for records (W3) and defined by hand for anything else. Format options are named arguments: `read<[n]Int>(base: 1)`, `print(xs, sep: "\n")`. `read>(directed: false, weighted: true)` is ordinary library code. Status: partial (`read` is still compiler-special for some types). ## W12. Costs and library lints (P12) Every public signature's first doc line states its cost: `/// O(log n).` `cpl explain` and hover show it. Libraries may declare lints with a code, message and codemod (`#lint(L7001, "...")`) and `#on_unimplemented("...")` messages on traits. `assert` runs in checked builds and, opted in as `asserts`, in release (chapter 9). Status: doc convention only. ## W13. Modules, pins and codemods (P13) `use std.graph.{bfs, Graph}`; prelude names need no `use`. A library may mark a name deprecated with a replacement that `cpl fix` applies: `#deprecated(use: "xs.sort(by: f)")`. Status: partial (codemods are compiler-side). ## W14. Inline C++ (P14) `@cpp("...")` bodies are allowed in any library, with the signature checked at the boundary and the C++ included once in the bundle. Status: partial. ## W15. Precomputation (P15) A top-level `let` is computed once before the first test (`let C = Comb>(N)`). Compile-time evaluation is not part of the spec: contest tables are cheap at start-up, and baking them would grow the bundle. Status: checks. ## W16. Contexts (P16): deferred `with io(base: 1)` and friends wait for the program-shape design. Until then a dream passes the option where it is used. Five dreams use contexts; they are listed in `delta/parser-gaps.md`. --- # 13. Lowering to C++ URL: /docs/ref/core/13-lowering This is the normative specification ([source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/core/13-lowering.md)). For a gentler introduction, start with the [guides](/docs/guides). Status: draft for 0.3.0. This is the contract between the language and the generated C++17: what each form becomes, what it costs, and what `cpl explain` reports. Sources: decisions 31, 52, 148, 149; archived `design/spec/18`; `03-numbers-layout.md` for widths and niches. ## 13.1 The output file - One deterministic C++17 file: a stamp, the used runtime pieces, the used library instances, then `main`. Same source and pins give the same bytes. Warn above 32 KB (the target for every solution), fail at 64 KB (profile-adjustable). (R13.1.1) - `main` starts a thread with the profile's stack (default 1 GB, halving down to 8 MB) and runs the program on it. (R13.1.2) - Input is one bulk `fread` and a hand-written parser; output is one buffer written at exit or flush. (R13.1.3) - Release builds compile with the profile's flags and emit no checks (chapter 9). The lowering adds no undefined behaviour to valid programs, and avoids it wherever that is free: signed arithmetic that may overflow is done in unsigned and cast back, shifts are masked, and every array is filled at construction. Unchecked indexes and `x!` on an invalid program are as unsafe as the same C++ (§9.2). (R13.1.4) ## 13.2 Values | Form | C++ | |---|---| | `Int`, ranges | `int64_t` in locals; storage at the range's width (`uint8_t` ... `int64_t`) (R13.2.1) | | `U64`, `I128`, `F64`, `Bool`, `Char` | `uint64_t`, `__int128`, `double`, `bool`, `char` (R13.2.2) | | position `v: V` | unsigned of `V`'s storage width (R13.2.3) | | cut | the same width, holding the count before it (R13.2.4) | | `?T` with a niche | `T`'s storage with the niche value as `None` (R13.2.5) | | `?T` without one | `T` plus a flag byte, aligned (R13.2.6) | | tuple, record, struct | a C++ struct, fields in storage order (R13.2.7) | | enum | niche-filled payload, or tag beside the largest payload (R13.2.8) | | `[D]T` | pointer plus count, heap buffer; never a stack VLA (R13.2.9) | | `List`, `Str` | an owned growable buffer (`std::vector`-like runtime type) (R13.2.10) | | `Mod

` constant | `uint32_t` or `uint64_t` with Montgomery or Barrett constants folded (R13.2.11) | | `Mod(p)` runtime | the same plus constants in the fresh type's static slot (R13.2.12) | | fresh-type data | one static slot per declaration site, saved and restored across recursive re-entry (R13.2.13) | Large static arrays (over 4 KB) and every runtime-sized array live on the heap. Locals of plain types live in registers or the stack. ## 13.3 Functions, closures, generators - Every generic instantiation is a separate C++ function with a mangled name; there are no C++ templates in the output for language generics. (R13.3.1) - A function value with a known target is passed as an empty struct and inlined; captures are passed as references at each call (chapter 6). There is no `std::function` and no indirect call. (R13.3.2) - A non-recursive generator inlines its body with the loop body in place of `yield`. A recursive generator becomes a recursive function taking the loop body as a parameter; when the body can `break` or `return`, a stop flag is threaded through that specialization only. (R13.3.3) - `@memo(array)` is a lazily allocated dense table of `?R` (jagged when bounds depend on earlier parameters); `@memo(map)` is an open- addressing table keyed by the parameters' storage. (R13.3.4) - Views are ordinary structs holding a pointer (lent) or the value (owned) plus their closures; walking them is a loop with no allocation. (R13.3.5) ## 13.4 Ownership Ownership has no runtime representation. Lends are pointers or references, moves are bitwise and leave the source dead (no destructor runs for a moved-from value), and `.clone()` is an explicit deep copy. A struct whose fields may be lent or owned is monomorphized on that choice only when the field's storage differs (a lent `List` is a pointer, an owned one is the buffer); `cpl explain` lists such copies. ## 13.5 Library specializations Each library structure documents its representation and every law-selected specialization, and codegen picks exactly that one: iterative bottom-up segment trees in one flat array, no push-down when tags commute, sliding folds by group/selective/general, sparse tables for idempotent ops, CSR graphs, `Rooted` arrays in preorder. `cpl explain` names the choice and the law that allowed it. ## 13.6 What `cpl explain` reports For any program: every type's size, storage order, padding and niche; every array's element width and peak bytes at the input bounds; total peak memory against the profile; each specialization and the law or bound behind it; each check remaining in checked builds and which are kept in release; each `@cache`, `@trusted` and `@cpp` site; each generic instance and context copy with its output bytes. The LSP shows the same data inline (`tools/lsp.md`). ## 13.7 Later Profile-driven vectorization: a judge profile names the instruction set (`isa: avx2`), codegen emits the matching `#pragma GCC target`, narrows arithmetic where ranges allow and vectorizes provable loop shapes; `explain` says which loops vectorized and why not. ## 13.8 Cost model tables (migrated from design/COST.md) # Cost model Every core form, what it lowers to in C++17, what it costs, and what each build checks. "Costs are visible" is checked here: each row names a test snippet under `tests/cost/` whose emitted C++ and `cpl explain` output must match the row. A row without a passing snippet is unverified; a form whose real lowering is worse than its row is a bug, and a deliberate exception is listed under Debt. Status: no row has its snippet yet, so every row is a target, not a measurement. Rows land verified one at a time. Rules every row follows: - Anything that looks O(1) is O(1); anything O(n) or allocating looks it. - No `std::function`, virtual call, hidden heap allocation or hidden traversal unless the row says so. - Debug and release differ only in checks, never in results for valid programs. ## Scalars | Form | Lowers to | Time | Alloc | Debug checks | Release checks | |---|---|---|---|---|---| | `Int` arithmetic | `int64_t` ops | O(1) | none | overflow traps | wraps | | range type `lo..=hi` storage | narrowest of `int32_t`/`uint32_t`/`int64_t` | O(1) | none | store into a range-typed place traps if out of range | same | | `/`, `%` | floor/Euclidean helper (one extra branch) | O(1) | none | division by zero traps | same | | `**` | square-and-multiply | O(log k) | none | overflow traps | wraps | | `Mod

` ops | `uint32_t` with constant-divisor reduction | O(1); `inv` O(log P) | none | none | none | | chained comparison | one comparison per link, operands evaluated once (§130) | O(links) | none | none | none | ## Absence | Form | Lowers to | Time | Alloc | Debug | Release | |---|---|---|---|---|---| | `?Int`, `?V`, `?range` | niche value in the same word (`Int` excludes `INT64_MIN`) | O(1) | none | none | none | | `?T` for other `T` | value + flag | O(1) | none | none | none | | `x!` | load | O(1) | none | traps on `none` unless flow facts prove it | same | | `x ?? y`, `?`, `none + x` | branch | O(1) | none | none | none | ## Index spaces and collections | Form | Lowers to | Time | Alloc | Debug | Release | |---|---|---|---|---|---| | `domain V = lo..=hi` | integer; runtime-sized domains read one hidden global slot (saved/restored on recursive re-entry) | O(1) | none | none | none | | `D.cuts` cut domain | integer | O(1) | none | none | none | | `a[v]` with `v: V`, `a: [V]T` | unchecked load | O(1) | none | none | none | | `xs[i]` on `List`/`Str` | load | O(1) | none | bounds check unless proven | same | | range `l..r` / cut range `j..i` | two integers; cut range → position range is free (§124) | O(1) | none | none | none | | slice `xs[l..r]` | view (`ptr`, `len`) (§123) | O(1) | none | bounds check unless proven | same | | `[V]T = x` | one heap array, filled | O(n) | heap, once | none | none | | `[f(x) for x in s]` (no filter) | reserved vector + loop | O(n) | heap, once (reserved) | none | none | | `xs.push(x)` | amortized vector push | O(1) amortized | amortized | none | none | | `xs.sort(by: k)` | `std::sort` with inlined key | O(n log n) | none | none | none | | `for x in xs` / `for v in V` / product domains | plain loop / nested integer loops | O(n) | none | none | none | ## Binding, control and functions | Form | Lowers to | Time | Alloc | Debug | Release | |---|---|---|---|---|---| | `let`, `var`, `let ... else`, `if let` | locals and branches | O(1) | none | none | none | | labelled `break`/`continue`, loop `else` (§125) | `goto` / flag-free branch | O(1) | none | none | none | | non-recursive generator in `for` | inlined; each `yield` runs the body in place | as written | none | none | none | | recursive generator in `for` with `break`/`return` (§126) | recursive function, body inlined at the `yield`; one stop branch per frame only when the body can exit | as written + 1 branch/frame | none | none | none | | closure argument | template functor parameter, inlined (`cpl explain`: static) | O(1) call | none | none | none | | recursive lambda / nested `fn` (§127) | self-passing generic lambda | direct call | none | none | none | | operator value (`by: <`, `+`) | functor, inlined | O(1) | none | none | none | | `@memo` on provably small bounds | flat table | O(1) lookup | heap, once | none | none | ## Mutation and places | Form | Lowers to | Time | Alloc | Debug | Release | |---|---|---|---|---|---| | `x op= y` (statement) | in-place op | O(1) | none | as for the op | as for the op | | `x min= y` / `max=` as a Bool (§129) | one compare + store | O(1) | none | none | none | | `let k = mut a[i]` | reference, index evaluated once | O(1) | none | none | none | | `m[k] += 1` on `Map` | one lookup, inserts default (§128) | O(1) expected | may insert | none | none | | return of a container | move (§128) | O(1) | none | none | none | | `let b = a` (heap value, last use) | move | O(1) | none | none | none | | `a.clone()` | deep copy | O(size) | heap | none | none | | `x.take()` | move out, leave empty | O(1) | none | none | none | | `a.swap(i, j)`, `swap(mut a, mut b)` | swap | O(1) | none | none | none | | `.absorb(mut other)` | small-into-large drain | O(min size) | amortized | none | none | ## I/O | Form | Lowers to | Time | Alloc | Debug | Release | |---|---|---|---|---|---| | `read()` | buffered fast reader, typed parse | O(input) | none beyond the value | declared bounds checked | same | | `print(...)` | buffered writer | O(output) | none | none | none | ## Debt (forms that cost more than their row) | Form | Today | Target | Owner | |---|---|---|---| | closures stored in struct fields, recursive local closures, fn params of recursive fns, reassigned fn slots | `std::function` | template parameter or self-passing lambda | codegen | ## Enforcement Each row gets one snippet `tests/cost/

.cp` plus assertions on its emitted C++ (e.g. no `std::function`, no allocation inside the loop, the expected integer width) and on `cpl explain --json`. `scripts/check.sh` runs them; a new core form lands with its row and snippet in the same commit. --- # Containers (std.bitset, std.bag, std.interval, std.dsu, std.heap, std.deque, std.marks, std.hashmap, std.seq.Compressed) URL: /docs/ref/lib/containers Normative text from [spec/lib/containers.md](https://github.com/ryanbai1412/cp-lang/blob/main/spec/lib/containers.md). > **0.3.0 status.** This chapter is the family's design survey and API. > Where it disagrees with the core chapters or the aligned rounds, they > win: `core/03-numbers-layout.md` (four number types, no `I32`/`U32`, > `Mod

` not `Mint`), `core/05-ownership.md` (constructors own their > results), `core/07-sequences.md` (capabilities, views keep keys), > `lib/ops-ranges.md` (`Op`/`Monoid`/laws, `each(...)`, no > `RangeFenwick`, `MinHeap`/`MaxHeap` as `Heap(by:)`) and > `lib/sequence-patterns.md`. The stubs in `std/` are the signatures of > record. Reconciliation of this text is tracked in `delta/`. Status: design for the CP Lang standard library containers area (`plan/STDLIB.md` §4.8–4.9). Every type here is ordinary CP Lang code using only the public language, documented intrinsics, and other stdlib modules — no compiler privilege. ## 1. Contest pattern survey This survey is grounded in Codeforces Div. 1, AtCoder Grand/ARC/WTF, ICPC World Finals, KACTL, AtCoder Library (ACL), and `proto/ports/ecnerwala/*_orig.cpp` plus `research/frictions/*.md`. ### 1.1 Ordered sets, maps, and multisets with rank and cursors Contestants reach for ordered balanced trees for four distinct jobs: - **Neighbour queries and local walks.** Given a dynamic set or multiset, find the predecessor/successor (`last_lt`, `first_gt`) and walk a few steps forward or backward in O(1) amortized per step. In `cf2066e_orig.cpp`, ecnerwala keeps `std::set>` (adding a unique id to get a multiset with O(1) erase and unique handles) and walks `rbegin()` downwards up to `sqrt(M)` steps while also reading `std::prev(it)` and `std::next(it)` on every insert and erase. Without O(1) cursors, each step re-walks from the root, turning O(q sqrt(M)) into O(q sqrt(M) log n) — a 6.11x slowdown and TLE in `research/frictions/cf2066e.md`. - **Order statistics.** `rank(k)` (count of elements `< k`), `nth(i)` (0-based k-th smallest), and `count_range(lo, hi)`. KACTL provides `OrderStatisticTree` (GNU PBDS `tree_order_statistics_node_update`). Ports `noi22p5`, `noi20p4`, `ccc05s5`, `cf2262b` all need order statistics. - **Monotone predicate search on the tree.** In `cf2262b`, the prefix maxima increase in both position and value, so one ordered set answers "first maximum whose value exceeds `s`" in O(log n) without keeping a second `Map` and a `Fenwick` in sync (`research/frictions/cf2262b.md`). - **Small-to-large merging.** `take()` in O(1) plus `swap` and draining the smaller container into the larger. Builtin `Set` and `Map` cover basic ordered sets/maps (lowering to `std::set`/`std::map`, or salted `std::unordered_*` when order is never observed), but they do not carry subtree sizes, cannot answer `rank`/`nth`/ `bsearch_first`/`bsearch_last`, and are not multisets. `std.bag` owns the augmented ordered containers: `SortedBag` (multiset with rank, cursors, monotone search, and recycled nodes) and `SortedSet` / `SortedMap` when distinct keys with order statistics and cursors are needed. ### 1.2 Interval partition maps (ODT / Chtholly tree) Painting ranges of a 1D array or HLD chains with a value/timestamp and processing every overwritten run `(range, old_val)` is ubiquitous in CF Div. 1 and ICPC (color-overwrite sweeps, HLD path paint as in `cf2237h`, active-segment maintenance, amortized O((n + q) log n) total runs created and destroyed). In `cf2237h.cp` (`research/frictions/cf2237h.md`), hand-rolling this over `Map` takes ~25 lines of fragile `split(l)`, `split(r)`, `remove(pos)!`, and manual run-length initialization — and forces leaving the nominal `tree.Pre` domain via `.ord`. Neither KACTL nor ACL ships an interval partition map; contestants copy-paste the same `split`/`assign` loop and debug off-by-ones. `std.interval.IntervalMap` makes the partition invariant a type over any domain `D`. ### 1.3 Disjoint-set union (DSU) ACL ships `dsu` (path compression + union by size + `groups`). KACTL ships `UnionFind` and `RollbackUF` (undo to `time()`). Across the corpus (56 port files, including `cf2069f`, `cf2222f`, `cf2237h`, `cf2150f`, `wtf26a`), four variants recur: - **Plain DSU with optional rollback (`Dsu`).** Fast path halving O(alpha(n)) when `mark()` is never called; switches to union-by-size without path compression O(log n) once `mark()` is called so `undo_to(snap)` restores exact state in O(1) per undone unite. - **Payload-carrying DSU (`DsuOf`).** Each component carries a `T` combined by `join(val_a, val_b)` in argument order `(a, b)` regardless of which root union-by-size keeps. This covers both commutative aggregates (sum, min, max, first representative in `cf2222f`) and directional skip-DSU (`(_, b) => b` in `cf2237h`), with full rollback of merges and `set`s. - **Bipartite / parity DSU (`ParityDsu`).** Tracks `x[a] xor x[b] == d`, contradiction count (`consistent`), and rollback (`mark`/`undo_to`). - **Weighted / potential DSU (`PotentialDsu`).** Tracks additive difference constraints `pot(b) - pot(a) == d` (`diff(a, b) -> ?Int`, contradiction detection, plus optional rollback via `Mark`). Promoted from `examples/local-lib/ds/potential_dsu.cp`. - **Companion rollback array (`RollbackArray`).** Fixed-domain `[D]T` with `Mark`-typed `mark()`/`undo_to(snap)`, promoted from `examples/local-lib/ds/rollback_array.cp` and unified onto `Mark`. ### 1.4 Heaps > Superseded by `std/heap.cp`: one type per shape (`Heap`, `ErasableHeap`, > `IndexedHeap`, `MeldHeap`) with `by:`; `MinHeap`/`MaxHeap` are aliases of > `Heap`, `peek` returns an unnamed `?(D, K)`, and `of(xs, by:)` builds in O(n). `MinHeap` and `MaxHeap` (chosen by name, never a hidden comparator flag; mixed tie-breaking via `Desc`) cover standard priority queues, Dijkstra, and greedy scheduling. Three gaps appear across contests: - **O(n) bottom-up construction (`of(xs)`).** Floyd's heapify builds a heap in O(n) instead of O(n log n) pushes. - **Arbitrary removal (`ErasableMinHeap`, `ErasableMaxHeap`).** The two-heap lazy-deletion idiom (`live` + `dead`) gives O(log n) amortized `remove(x)` at binary-heap constant factor (2–3x faster and far less memory than a balanced tree when only min/max is needed). - **Keyed decrease/update-key (`IndexedMinHeap`, `IndexedMaxHeap`).** Over a domain `D`, maps each active key `d: D` to a priority `T` with O(log n) `set(d, val)`, `remove(d)`, `pop() -> ?(D, T)`, and O(1) `get(d) -> ?T` / `contains(d)`. Avoids stale-entry memory blowup in dense Dijkstra/Prim and dynamic scheduling. - **One pop per key (`Settle(best: min)`).** `offer(k, p)` keeps the best priority for a key not yet popped and ignores keys already popped; `pop() -> ?(K, P)` settles the best key. Dijkstra's frontier, Prim's, and "settle answers from the largest down" without a done-flag side array. ### 1.5 Deques and sliding-window queues `Deque` is a ring buffer with O(1) amortized ends and O(1) random access (`get`, `set`, `first`, `last(k)`). Two classic contest structures sit directly beside it in `examples/local-lib/ds/`: - **`MonoDeque`** — sliding-window minimum or maximum in O(1) amortized per element (`push(at, val)`, `drop_before(min_at)`, `best`). Used in sliding-window DP, convex/Monge DP (`cf2183h`), and range-min sweeps. - **`TwoStackFold`** — FIFO queue with O(1) `fold` over any `Monoid` without requiring an inverse (gcd, bitwise OR, matrix products). ### 1.6 Bitsets `Bitset` packs a set of positions of domain `D` into 64-bit words for O(K / 64) set algebra and shift DP (`cf2147h`, `cf2187d`, `ioi04p5`, `yac1p4`). Four friction points surfaced in ports: - **Knapsack performance trap (`cf2187d`).** The obvious loop `for w in ws: reach.union(reach.shifted(w))` allocates a fresh `Bitset` per step and is O(n * W / 64) — 10x slower than the C++ original on 100k equal weights. Two fixes belong together: an in-place non-allocating `shift_or(k)` / `shift_up(k)` for custom shift DPs, and a stdlib `subset_sums(weights)` that applies the folklore binary carry (turning duplicate weights into O(sqrt(sum)) items in O(K sqrt(S) / 64)). - **Word-level negative shifts.** `shifted(-k)` currently loops bit-by-bit in O(K) instead of word-by-word in O(K / 64). - **Navigation and range queries.** `first`, `last`, `prev(i)` (completing `next(i)`), `clear()`, and `count_below(i)` (all O(K / 64)). - **Non-mutating single-bit helpers and search.** `with(i)`, `without(i)`, and `find(pred)` (from `cf2147h.md`, avoiding `var rest = alive; rest.remove(v)`). ### 1.7 Hash maps and sets Builtin `HashMap` and `HashSet` already emit `std::unordered_map` and `std::unordered_set` with a salted `splitmix64` hash (`cpl::CpHash`), defeating Codeforces anti-hash hacks by default. However, `std::unordered_map` allocates one heap node per entry (high RSS and cache misses). In C++, contestants reach for `gp_hash_table` or a custom open-addressing flat table (`FlatMap`) when `n >= 2e5` and hash lookups are the bottleneck. `std.hashmap` provides `FlatMap` (open-addressing linear probing over `Int` keys with salted `splitmix64`, power-of-two table, load factor <= 0.5, O(1) expected lookup/insert/remove, ~16 bytes/entry vs ~48 bytes for `std::unordered_map`). It is explicit by name — never silently substituted for `HashMap`. ### 1.8 Sparse and coordinate-compressed indexing Three complementary patterns appear across contests: - **Offline coordinate compression (`std.seq.compress` -> `Compressed`).** Sorts values, deduplicates, and returns a fresh domain `xs.D`. Today it has `get`, `slice`, `len`, `at`, `first_ge`, `last_le`. It lacks `first_gt`, `last_lt` (the rest of the 4-name sorted lookup family), `try_at(val) -> ?D`, `contains(val) -> Bool`, and `range(lo, hi) -> Range` (turning value bounds directly into a domain `Range`). - **Online bidirectional interning (`std.marks.Interner` or `std.seq`).** Assigns dense `0..len` ids to arbitrary keys on the fly (`id`, `get`, `key`, `keys`). Promoted from `examples/local-lib/ds/interner.cp`. - **O(1)-clear epoch tables (`std.marks.Marks` and `MarkMap`).** `Marks` already gives an O(1)-clear visited set over `D` using a 32-bit generation stamp. `MarkMap` generalizes it to an O(1)-clear sparse array over `D` with a default value `default: T` (`get`, `set`, `contains`, `remove`, `clear` all O(1)), replacing manual epoch arrays in BFS, Dinic, and per-query DP resets. --- ## 2. Coherent API design Every container follows `plan/STDLIB.md` §2: - Collection verbs: `add`, `remove`, `contains` (`x in c`), `len`, `is_empty`, `clear`, `take`. - Sorted lookup family everywhere a total order exists: `first_ge`, `first_gt`, `last_le`, `last_lt`, plus `first`, `last`, `pop_first`, `pop_last`. - Fallible lookups return `?T`; trapping twins have the short name (`at` vs `try_at`, `get` returning `?V` on maps). - Options are named arguments (`differ:`, `inclusive:`), never `_by` variants. - Every public item documents its time and memory cost in `///`. - Domains are preserved end-to-end: `Bitset`, `IntervalMap`, `Dsu`, `DsuOf`, `ParityDsu`, `PotentialDsu`, `RollbackArray`, `IndexedMinHeap`, `IndexedMaxHeap`, `Marks`, `MarkMap`, `Compressed`. ### 2.1 `std.bitset` ```cp struct Bitset // O(K / 64) words, 1 bit/pos fn new() -> Bitset // O(K / 64) fn full() -> Bitset // O(K / 64) fn from(a: [D]Bool) -> Bitset // O(K) fn contains(self, i: D) -> Bool // O(1) fn add(mut self, i: D) // O(1) fn remove(mut self, i: D) // O(1) fn toggle(mut self, i: D) // O(1) fn with(self, i: D) -> Bitset // O(K / 64), non-mutating copy fn without(self, i: D) -> Bitset // O(K / 64), non-mutating copy fn clear(mut self) // O(K / 64) @get fn len(self) -> Int // O(K / 64) @get fn count(self) -> Int // O(K / 64) @get fn is_empty(self) -> Bool // O(K / 64), early exit @get fn first(self) -> ?D // O(K / 64) @get fn last(self) -> ?D // O(K / 64) fn next(self, i: D) -> ?D // O(K / 64), first >= i fn prev(self, i: D) -> ?D // O(K / 64), last < i fn count_below(self, i: D) -> Int // O(K / 64), count < i fn union(mut self, o: Bitset) // O(K / 64) fn intersect(mut self, o: Bitset) // O(K / 64) fn subtract(mut self, o: Bitset) // O(K / 64) fn symmetric(mut self, o: Bitset) // O(K / 64) fn bitor(self, o: Bitset) -> Bitset // O(K / 64) fn bitand(self, o: Bitset) -> Bitset// O(K / 64) fn bitxor(self, o: Bitset) -> Bitset// O(K / 64) fn meets(self, o: Bitset) -> Bool // O(K / 64), early exit fn shifted(self, k: Int) -> Bitset // O(K / 64), signed k fn shift_up(mut self, k: Int) // O(K / 64) in place, k >= 0 fn shift_or(mut self, k: Int) // O(K / 64) in place: self |= self << k fn each(self) -> yields D // O(K / 64 + |self|) fn find(self, pred: D -> Bool) -> ?D // O(K / 64 + visited) fn subset_sums(weights: List) -> Bitset // O(K * sqrt(sum) / 64); binary-carry knapsack over 0..D.K ``` Laws: every set operation agrees pointwise with `[D]Bool`; `b.first` equals `b.next(D.first)`; `b.count_below(i)` equals `count(x < i for x in b.each())`; `b.shift_or(k)` equals `b | b.shifted(k)` without allocation; `subset_sums` agrees with brute-force 0/1 subset sums on random small weight multisets. ### 2.2 `std.bag` (augmented ordered multiset, set, and map with cursors) > Superseded in part: decision 103 replaces `first_ge`/`first_gt`/`last_le`/ > `last_lt`/`count_range` with `range(r)` views, and the monotone searches are > `first_true`/`last_true` (decision 137, `core/04-indices.md`), not > `bsearch_first`/`bsearch_last`. `drain(r)` is `drain_range(r)`. `SortedBag` is backed by a randomized treap over flat arrays with a recycled free list (eliminating memory leaks on erase, fixing `cf2066e.md` #2) and parent pointers so a `BagCursor` steps to `prev` / `next` in O(1) amortized (fixing `cf2066e.md` #1). Each node stores `(key, pri, cnt, sub, left, right, parent)`. ```cp struct BagCursor(id: Int) // opaque handle into a SortedBag struct SortedBag // O(log n) ops, O(distinct) mem fn new() -> SortedBag // O(1) fn of(xs: List) -> SortedBag // O(n log n) @get fn len(self) -> Int // O(1), total with multiplicity @get fn distinct(self) -> Int // O(1), distinct keys @get fn is_empty(self) -> Bool // O(1) fn clear(mut self) // O(1) fn take(mut self) -> SortedBag // O(1) fn add(mut self, x: K) -> Bool // O(log n); inserts one copy fn add_many(mut self, x: K, c: Int) // O(log n); inserts c >= 0 copies fn remove(mut self, x: K) -> Bool // O(log n); removes one copy fn remove_all(mut self, x: K) -> Int // O(log n); returns removed count fn count(self, x: K) -> Int // O(log n) fn contains(self, x: K) -> Bool // O(log n) @get fn first(self) -> ?K // O(log n) @get fn last(self) -> ?K // O(log n) fn pop_first(mut self) -> ?K // O(log n) fn pop_last(mut self) -> ?K // O(log n) fn first_ge(self, k: K) -> ?K // O(log n) fn first_gt(self, k: K) -> ?K // O(log n) fn last_le(self, k: K) -> ?K // O(log n) fn last_lt(self, k: K) -> ?K // O(log n) fn rank(self, k: K) -> Int // O(log n), count strictly < k fn count_range(self, lo: K, hi: K) -> Int // O(log n), count in [lo, hi) fn nth(self, i: Int) -> ?K // O(log n), 0-based fn bsearch_first(self, ok: K -> Bool) -> ?K // O(log n), monotone ok fn bsearch_last(self, ok: K -> Bool) -> ?K // O(log n), monotone ok // Cursor navigation: O(log n) to locate, O(1) amortized to step fn cursor_first(self) -> ?BagCursor // O(log n) fn cursor_last(self) -> ?BagCursor // O(log n) fn cursor_at(self, k: K) -> ?BagCursor // O(log n), exact key fn cursor_ge(self, k: K) -> ?BagCursor // O(log n), first >= k fn cursor_gt(self, k: K) -> ?BagCursor // O(log n), first > k fn cursor_le(self, k: K) -> ?BagCursor // O(log n), last <= k fn cursor_lt(self, k: K) -> ?BagCursor // O(log n), last < k fn key_of(self, c: BagCursor) -> K // O(1) fn count_of(self, c: BagCursor) -> Int // O(1) fn next_cursor(self, c: BagCursor) -> ?BagCursor // O(1) amortized fn prev_cursor(self, c: BagCursor) -> ?BagCursor // O(1) amortized fn entries(self) -> yields (key: K, count: Int) // O(n), ascending fn entries_rev(self) -> yields (key: K, count: Int) // O(n), descending fn to_list(self) -> List // O(n) ``` `SortedSet` wraps the same treap invariant with uniqueness (`add(x) -> Bool` is false if already present) and exposes the exact same `first_ge`/`first_gt`/ `range(r)` views, `rank`, `nth`, `bsearch_first`/`bsearch_last`, cursors, and `each`/`each_rev`. This directly solves `cf2262b.md` (collapsing `Set`, `Map`, and `Fenwick` into one `SortedSet`). Why not mutate `SortedBag` through a cursor (`erase(c)`)? Because a treap `split`/`merge` is already O(log n) and invalidates structural paths; keeping cursors read-only handles that remain valid until the next mutation avoids dangling-cursor traps while giving O(1) amortized `prev`/`next` and O(1) `entries_rev()` walks (which is exactly what `cf2066e` needs). Laws: `SortedBag` matches a sorted `List` on every op; `nth(rank(k))` is `first_ge(k)`; `count_range(lo, hi) == rank(hi) - rank(lo)` for `lo <= hi`; `entries_rev()` is the exact reverse of `entries()`; after `m` inserts and `m` removes, internal live node count is 0 and free-list recycling bounds array length to peak distinct keys. ### 2.3 `std.interval` (ODT / interval partition map) `IntervalMap` maintains a total partition of domain `D` into maximal half-open runs `[l, r)` mapped to values of `T` (where `T: Eq`). Internally it stores a `Map` keyed by `lo.ord` — every position in `0..D.K` belongs to exactly one entry, and adjacent entries have distinct values. ```cp struct IntervalMap // O(runs) memory; amortized O(log runs) fn new(init: T) -> IntervalMap // O(1); whole domain has value init fn from(a: [D]T) -> IntervalMap // O(D.K); compresses maximal runs fn at(self, i: D) -> T // O(log runs) fn run_at(self, i: D) -> (range: Range, val: T) // O(log runs) fn assign(mut self, r: Range, val: T, on_old: (Range, T) -> () = (_, _) => ()) // Amortized O((1 + overwritten) log runs); returns overwritten runs // in ascending order and coalesces adjacent equal runs. fn assign_point(mut self, i: D, val: T) -> T // O(log runs); assigns i..=i and returns previous value fn each(self) -> yields (range: Range, val: T) // O(runs) @get fn runs(self) -> Int // O(1), number of maximal runs ``` Why does `assign` take an optional `on_old: (Range, T) -> ()` callback instead of returning a `List` or being a `yields` generator? A `yields` generator borrowing `mut self` cannot guarantee the partition is left valid if the caller `break`s out early (and `cpl_ir::pushed::Feeds` does not push `mut self` yields), while returning a `List` allocates per call. An optional callback enforces partition completion, devirtualizes to an inlined template functor in C++ with zero heap allocation, and defaults to a no-op when overwritten runs are not needed. Laws: `IntervalMap` agrees at every `i in D` with a brute-force `[D]T` array under random `assign` and `assign_point` calls; adjacent runs in `each()` never have equal `val`; the runs partition `D` with no gaps or overlaps. ### 2.4 `std.dsu` Already ships `Mark`, `Dsu`, `DsuOf`, and `ParityDsu`. Additions: ```cp // Existing: Mark, Dsu, DsuOf, ParityDsu // New in std.dsu: struct PotentialDsu // O(alpha(n)), O(log n) after mark fn new() -> PotentialDsu // O(n) fn find(mut self, v: V) -> (root: V, pot: Int) // pot(v) - pot(root) fn unite(mut self, a: V, b: V, diff: Int) -> Bool // Records pot(b) - pot(a) == diff; false on contradiction fn diff(mut self, a: V, b: V) -> ?Int // pot(b) - pot(a), or None fn same(mut self, a: V, b: V) -> Bool fn size(mut self, v: V) -> Int @get fn components(self) -> Int @get fn consistent(self) -> Bool fn mark(mut self) -> Mark // O(1) fn undo_to(mut self, snap: Mark) // O(1) per undone unite struct RollbackArray // O(1) get/set/mark, O(changes) undo fn new(init: D -> T) -> RollbackArray // O(n), n = D.count; filled is new(_ => v) fn get(self, i: D) -> T // O(1) fn set(mut self, i: D, val: T) // O(1) fn mark(self) -> Mark // O(1) fn undo_to(mut self, snap: Mark) // O(1) per undone set ``` Also add `groups()` to `DsuOf` so it matches `Dsu`. All five rollback structures share the single nominal `Mark` type. Laws: `PotentialDsu` matches a hidden potential array `[V]Int` across random unites, contradictions, and rollbacks; `RollbackArray` matches full array snapshots across random `set`/`mark`/`undo_to` sequences. ### 2.5 `std.heap` > Superseded: see the note in 1.4 and `std/heap.cp`. ```cp // Existing: MinHeap, MaxHeap // Added to MinHeap and MaxHeap: fn of(xs: List) -> MinHeap // O(n) Floyd heapify fn of(xs: List) -> MaxHeap // O(n) Floyd heapify // New in std.heap: struct ErasableMinHeap // O(log n) amortized; two heaps fn new() -> ErasableMinHeap // O(1) @get fn len(self) -> Int // O(1) @get fn is_empty(self) -> Bool // O(1) fn clear(mut self) // O(1) fn take(mut self) -> ErasableMinHeap // O(1) fn push(mut self, x: T) // O(log n) fn remove(mut self, x: T) // O(log n); x must be present fn peek(mut self) -> ?T // O(log n) amortized fn pop(mut self) -> ?T // O(log n) amortized struct ErasableMaxHeap // same surface, largest first struct IndexedMinHeap // O(log n) push/set/remove/pop fn new() -> IndexedMinHeap // O(D.K) @get fn len(self) -> Int // O(1) @get fn is_empty(self) -> Bool // O(1) fn clear(mut self) // O(len) fn contains(self, k: D) -> Bool // O(1) fn get(self, k: D) -> ?T // O(1) fn set(mut self, k: D, val: T) // O(log n); insert or update fn remove(mut self, k: D) -> ?T // O(log n) @get fn peek(self) -> ?(key: D, val: T) // O(1) fn pop(mut self) -> ?(key: D, val: T) // O(log n) struct IndexedMaxHeap // same surface, largest first ``` Note on `ErasableMinHeap.peek`: takes `mut self` because purging lazy-deleted tops mutates the internal heaps; its doc states this explicitly. Laws: `MinHeap.of(xs)` pops elements in the exact order of `sorted(xs)`; `ErasableMinHeap` matches a sorted multiset on random push/remove/peek/pop; `IndexedMinHeap` matches a `[D]?T` array scanned for minimum on random `set`/`remove`/`pop`. ### 2.6 `std.deque` ```cp // Existing: Deque (add set(mut self, i: Int, x: T) and to_list(self) -> List) // Promoted from examples/local-lib/ds/: struct MonoDeque // O(1) amortized sliding min/max fn new(pick: (T, T) -> T) -> MonoDeque // pick is min or max fn by(better: (T, T) -> Bool) -> MonoDeque @get fn len(self) -> Int // O(1) @get fn is_empty(self) -> Bool // O(1) fn clear(mut self) // O(1) fn push(mut self, at: Int, val: T) // O(1) amortized fn drop_before(mut self, min_at: Int) // O(1) amortized @get fn best(self) -> ?T // O(1) struct TwoStackFold // O(1) amortized queue monoid fold fn new(op: M) -> TwoStackFold // op is a Monoid or bare op @get fn len(self) -> Int // O(1) @get fn is_empty(self) -> Bool // O(1) fn clear(mut self) // O(1) fn push(mut self, x: T) // O(1) fn pop(mut self) -> ?T // O(1) amortized @get fn fold(self) -> T // O(1) ``` ### 2.7 `std.marks` and `std.seq.Compressed` ```cp // Existing in std.marks: Marks // New in std.marks: struct MarkMap // O(1) get/set/remove/clear fn new(default: T) -> MarkMap // O(D.K) once fn get(self, v: D) -> ?T // O(1); None when unset fn set(mut self, v: D, x: T) // O(1) fn contains(self, v: D) -> Bool // O(1) fn remove(mut self, v: D) -> ?T // O(1); the old value fn clear(mut self) // O(1) epoch bump @get fn len(self) -> Int // O(1) @get fn is_empty(self) -> Bool // O(1) struct Interner // online key <-> 0..len id fn new() -> Interner // O(1) @get fn len(self) -> Int // O(1) @get fn is_empty(self) -> Bool // O(1) fn id(mut self, k: K) -> Int // O(1) expected (HashMap) fn get(self, k: K) -> ?Int // O(log n) fn key(self, idx: Int) -> K // O(1) @get fn keys(self) -> List // O(1) // Additions to std.seq.Compressed: fn try_at(self, val: T) -> ?D // O(log n) fn contains(self, val: T) -> Bool // O(log n) fn first_gt(self, val: T) -> ?D // O(log n) fn last_lt(self, val: T) -> ?D // O(log n) fn range(self, lo: T, hi: T) -> Range // O(log n); compressed [lo, hi) ``` ### 2.8 `std.hashmap` (open-addressing flat hash tables for `Int` keys) Builtin `HashMap` and `HashSet` remain the default for arbitrary hashable keys. `std.hashmap` adds an explicit open-addressing table for `Int` keys when constant factor and memory matter: ```cp struct FlatMap // O(1) expected; open addressing fn new(default_val: V, cap: Int = 16) -> FlatMap // O(cap) @get fn len(self) -> Int // O(1) @get fn is_empty(self) -> Bool // O(1) fn clear(mut self) // O(table_size) fn contains(self, k: Int) -> Bool // O(1) expected fn get(self, k: Int) -> ?V // O(1) expected fn set(mut self, k: Int, v: V) // O(1) expected fn remove(mut self, k: Int) -> ?V // O(1) expected (backward shift) @get fn items(self) -> yields (Int, V) // O(table_size); also keys, values ``` Uses a per-instance random `splitmix64` salt (initialized from `rand`) so anti-hash inputs cannot force O(n) probe chains, and backward-shift deletion so tombstones never degrade performance. ### 2.9 What stays user code - **Custom lazy treaps / implicit ropes** (`cf2084g2_orig.cpp` slope-trick treap with affine-per-index lazy tags, `examples/local-lib/ds/rope.cp`): every problem invents its own node payload and pushdown; a generic implicit treap belongs in `local-lib`, not a one-size-fits-all stdlib container. - **Persistent hashed multisets** (`cf2135f`): waits for a general `Arena` with 4-byte handles and struct field narrowing (`research/frictions/cf2135f.md`). - **Offline dynamic connectivity driver (`TimeTree.run` / `offline_over`)**: now ships in `std.timetree` using `mark`/`apply`/`answer`/`undo` callbacks (zero `TimeStep` allocation, 1 mark per tree node, devirtualized in C++). - **Two-heap running median**: 6 lines over `MaxHeap` + `MinHeap` (or one `SortedBag.nth(len / 2)` when O(log n) tree cost is fine). ### 2.10 Core features coordinated with the core-extensions lane None of these are special-cased in stdlib; all are general core improvements: - `for x in c` protocol for any struct with `each() -> yields T` (`Bitset`, `SortedBag`, `IntervalMap`, `FlatMap`). - `?.` optional chaining (`top_at.first_gt(c)?.l ?? I.end`, `cf2262b.md`). - Narrowing range-typed struct fields to 4 bytes (halves `SortedBag` / arena node RSS, `cf2135f.md`). - Scoped `defer` / `undo` for rollback safety across early returns (`cf2222f.md`). - Default-valued `Map`/`HashMap` and `.keys`/`.values` views (`cf2066c.md`). --- ## 3. Real contest problems written against this API ### 3.1 `cf2066e`: Tropical Season (`SortedBag` with cursors) Problem: maintain a multiset of barrel volumes under `+ a` / `- a` (`n, q <= 2e5`, `a <= 1e6`) and answer whether any `k > 0` has `sum(barrels < k) < k`, at least two barrels `>= k`, and every gap between consecutive barrels `>= k` at least `k`. Split at `RT = 1000`: walk the top barrels downward in O(1) per step via `entries_rev()` for large `k`, and track small gaps via `SortedBag` cursors. ```cp // Split bad k at RT = sqrt(1e6): large k walks downward from the largest barrel // in O(1) per step via entries_rev(); small k tracks the rightmost small gap // of each width 0..=RT. use std.bag.{SortedBag} let (n, q): (1..=200_000, 1..=200_000) = read() let RT = 1000 domain Small = 0..=RT var cur = SortedBag() var small_gaps: [Small]SortedBag = [Small] _ => SortedBag() var last_small: [Small]Int = 0 var cnt_small: [Small]Int = 0 var tot = 0 fn upd_gap(lo: Int, hi: Int, ins: Bool): let l = hi - lo if l > RT: return let d = Small(l) if ins: small_gaps[d].add(lo) else: small_gaps[d].remove(lo) last_small[d] = small_gaps[d].last ?? 0 fn insert_barrel(v: Int): tot += v if v <= RT: cnt_small[Small(v)] += 1 let _ = cur.add(v) let c = cur.cursor_at(v)! if cur.count_of(c) >= 2: upd_gap(v, v, true) else: let prv = cur.prev_cursor(c) let nxt = cur.next_cursor(c) if prv != None and nxt != None: upd_gap(cur.key_of(prv!), cur.key_of(nxt!), false) if prv != none: upd_gap(cur.key_of(prv!), v, true) if nxt != none: upd_gap(v, cur.key_of(nxt!), true) fn has_bad_k() -> Bool: var first_step = true var cur_val = 0 var cur_tot = tot var cur_gap = 0 for (nv, mult) in cur.entries_rev(): if first_step: first_step = false if mult >= 2: break cur_val = nv cur_tot = tot - nv cur_gap = nv else: cur_tot -= nv cur_gap = min(cur_gap, min(cur_val - nv, nv)) if cur_tot < cur_gap: return true if cur_gap <= RT or mult >= 2: break cur_val = nv var last_gap = 0 var cnt_big = cur.len var tot_small = 0 for k in 1..=RT: let d = Small(k - 1) last_gap max= last_small[d] cnt_big -= cnt_small[d] tot_small += (k - 1) * cnt_small[d] if cnt_big < 2: break if last_gap < k and tot_small < k: return true false ``` ### 3.2 `cf2237h`: Slime and Queries (`IntervalMap` + `DsuOf`) Problem: tree of `n` vertices, initial slime set, `q` queries moving a cursor from `cur` to `c` along the tree path, repainting the path with timestamp `t_now` and greedily consuming older slime buckets. `IntervalMap` replaces the 25-line hand-rolled ODT and eliminates `.ord` escapes. ```cp // Repaint each HLD chain of the path (cur -> c) with timestamp t_now using // IntervalMap, then greedily drain slime buckets newest-first // via directional skip-DSU (DsuOf with (_, b) => b). @!multitest use std.dsu.{DsuOf} use std.interval.{IntervalMap} let (n, m, q): (2..=100_000, 2..=100_000, 1..=100_000) = read() domain V = 1..=n let edges: [0..n - 1](u: V, v: V) = read() let tree = Rooted(Graph.undirected(edges), V.first) let init_slime: [0..m]V = read() var cur = init_slime[m - 1] domain Time = 1..=q + 2 var segs = IntervalMap(Time(1)) for v in init_slime: segs.assign_point(tree.pos(v), Time(2)) var bucket = DsuOf( _ => (prv: None, cnt: 0), (_, b) => b) bucket.set(Time(2), (prv: None, cnt: m)) var tot_ans = 0 var ans: List = [] for t_now in Time(3)..: let c = read::().cyc(tot_ans) var chunks: List<(t: Time, w: Int)> = [] for (range, _) in tree.chains(cur, c): segs.assign(range, t_now, on_old: (r, t) => chunks.push((t: t, w: r.len))) cur = c sort(mut chunks, by: x => desc(x.t)) var (cur_cnt, cur_ans) = (0, 0) for chunk in chunks: var w = chunk.w var it: ?Time = chunk.t while let u = it, w > 0: let (prv, cnt) = bucket.get(u) let take = min(cnt, w) cur_cnt += take w -= take bucket.set(u, (prv: prv, cnt: cnt - take)) if take == cnt: if let p = prv: bucket.unite(u, p) else: it = None cur_ans += w bucket.set(t_now, (prv: t_now - 1, cnt: cur_cnt)) tot_ans += cur_ans ans.push(tot_ans) print(ans) ``` ### 3.3 `cf2187d`: Cool Problem (`Bitset` + `subset_sums`) Problem: given string of `0`, `1`, `?` (`n <= 1e5`), compute the sum of all distinct final values reachable by filling `?`. After the first `?`, each later `?` contributes an optional half-gap whose total sum is `<= m`, so `subset_sums` computes all reachable sums in O(m sqrt(m) / 64) without manual binary carries. ```cp // Half-gaps sum to at most m, so binary-carry bitset subset_sums finds every // reachable offset in O(m sqrt(m) / 64) with zero manual carry bookkeeping. use std.bitset.{subset_sums} domain Half = 0..=m let reach = subset_sums(half_gaps) var cool: Set = Set() for i in reach.each(): cool.add(end_f[Pos(2 * i.to_idx + p0)]) cool.add(end_f[Pos(2 * i.to_idx + p1)]) print(sum(Z(v) for v in cool)) ``` ### 3.4 `cf2262b`: Prefix Maxima Champions (`SortedSet` with `bsearch_first` + `range(r).len`) Problem: reverse removals into insertions; maintain prefix maxima and count how many prefix maxima are eaten by champions. `SortedSet` holds the prefix maxima in one structure, answering both the monotone value search (`bsearch_first`) and range count (`range(r).len`) in O(log n). ```cp // Prefix maxima increase in both position and value, so one SortedSet // answers both "first maximum > s" (bsearch_first) and "how many in c..stop" // (range(c.l..stop).len), replacing three structures kept in sync by hand. var tops = SortedSet() let s = total.sum(c.l..stop) let reach = if let q = tops.bsearch_first(q => a[q] > s): q.l else: I.end let eaten = tops.range(c.l..stop).len - 1 ``` ### 3.5 `cf2069f`: Graph Inclusion (`Dsu` + `Mark` rollback) Problem: answer `components(A) - components(A + B)` after each edge toggle in graphs A and B (`n, q <= 4e5`). Two `Dsu` instances share the `Mark` protocol (`mark()` / `undo_to(snap)`), switching cleanly from O(alpha(n)) to O(log n) rollback on the first mark. ```cp var (a, ab) = (Dsu(), Dsu()) fn solve(span: Range, live: List): let snap = (a.mark(), ab.mark()) var rest: List = [] for e in live: if e.on.start <= span.start and span.end <= e.on.end: if e.in_a: a.unite(e.x, e.y) ab.unite(e.x, e.y) elif e.on.start < span.end and span.start < e.on.end: rest.push(e) if span.len == 1: ans[span.first!] = a.components - ab.components else: let m = span.mid! solve(span.start..m.r, rest) solve(m.r..span.end, rest) a.undo_to(snap.0) ab.undo_to(snap.1) ``` --- ## 4. Maximalist roadmap After landing the v1 surface above and rewriting the affected ports (`cf2066e`, `cf2237h`, `cf2187d`, `cf2262b`, `cf2147h`): - **B-tree `SortedBag` / `SortedSet` (optional):** `BagNode` now packs 32-bit `pri`/`left`/`right`/`par` into one 40-byte cache line (`sorted_range` `0.61x` vs C++ treap, `sorted_set` `1.26x` vs PBDS `rb_tree_tag`). Moving to a cache-friendly B-tree would close the remaining 1.26x treap-depth gap vs PBDS red-black trees if needed. --- ## 5. Deferred dream gaps (not in the design) - **`SortedBag.sum` (1 user):** deferred because only a single dream asks for prefix/range sums on `SortedBag`. If a second user appears, the general mechanism is a monoid-augmented `SortedBag` (matching `SegTree` / `Fenwick`), not an ad-hoc `.sum` field on `SortedBag`. - **`PMultiset`:** now in `std.persistent` (no longer deferred). - **`MinHeap(by:)` (resolved by existing idiom):** `cf2159f.cp` reads cleanly with `stdlib/heap.cp`'s documented `(key, payload)` / `(key, desc(v))` entry idiom (`var heap = MinHeap<(Int, Seg)>()`), with zero comparator indirection. - **Dynamic bitset (`DynBitset`):** for problems where the bitset width is computed inside a loop without a domain in scope. - **Persistent `Arena` + `PMultiset`:** typed 4-byte arena handles so persistent segment trees, tries, and `cf2135f` need zero raw-int pools. - **Group-valued `PotentialDsu`:** unify `ParityDsu` (Z/2Z) and `PotentialDsu` (Z) over any `Group` once `std.algebra` adds `Group`. --- ## 6. Matched C++17 benchmarks (`bench/containers/run.sh`) All 13 matched C++17 benchmarks (`g++ -std=c++17 -O2`, best of 3 runs, identical stdout verified): **p50 = 0.95x**, **max = 1.26x** (`sorted_set`). 10 of 13 benches run at `<= 0.98x` matched C++ (`interval_map` `0.56x`, `sorted_range` `0.61x`, `hash_antihash` `0.64x`, `hash_insert` `0.68x`, `hash_lookup` `0.79x`, `min_heap` `0.92x`, `flatmap` `0.95x`, `bitset` `0.96x`, `ordered_map_set` `0.96x`, `monodeque` `0.98x`). Profiling notes for the three rows above `1.10x`: - **`dsu` (`1.15x` wall, `30 ms` vs `27 ms` user):** `Dsu` now uses one packed 32-bit negative-size array (`4 B/vertex`) and `unchecked:` `find_ord`. The remaining ~3 ms is `cpl::umod` + `cpl::pos` in the benchmark's 3M random domain conversions (`V(Int((s >> 33) % U64(n)))`). - **`deque` (`1.14x`, `42.0 ms` vs `36.7 ms`):** raw `List` ring storage (eliminating `OptInt` and per-`get` option unwraps, 2x less memory), `Deque.reserve(cap)` preallocation, and cached power-of-two `mask` brought `deque` down from `1.95x`. The remaining ~5 ms vs `std::deque` is the release `assert 0 <= i < n` bounds check and `cpl::umod` on 2M random reads. - **`sorted_set` (`1.26x`, `112.9 ms` vs `89.5 ms` PBDS `rb_tree_tag`):** packing `BagNode` into one 40-byte struct array and switching `add`/`remove` to single-pass BST descent + rotation without sibling `pull` cut `sorted_set` from `2.55x` (`240.8 ms`) to `1.26x` (`112.9 ms`) and `sorted_range` from `1.00x` to `0.61x`. The remaining `1.26x` vs PBDS is the expected randomized treap depth (`1.386 log2 n`) vs red-black tree (`~1.05 log2 n`). --- # std.flow: flows, cuts and matchings URL: /docs/ref/lib/flows Normative text from [spec/lib/flows.md](https://github.com/ryanbai1412/cp-lang/blob/main/spec/lib/flows.md). > **0.3.0 status.** This chapter is the family's design survey and API. > Where it disagrees with the core chapters or the aligned rounds, they > win: `core/03-numbers-layout.md` (four number types, no `I32`/`U32`, > `Mod

` not `Mint`), `core/05-ownership.md` (constructors own their > results), `core/07-sequences.md` (capabilities, views keep keys), > `lib/ops-ranges.md` (`Op`/`Monoid`/laws, `each(...)`, no > `RangeFenwick`, `MinHeap`/`MaxHeap` as `Heap(by:)`) and > `lib/sequence-patterns.md`. The stubs in `std/` are the signatures of > record. Reconciliation of this text is tracked in `delta/`. The top-down design of the flows-and-matching area: the contest patterns it must cover, one API that covers them, the laws each function keeps, how the area uses domains, and what stays user code. `plan/STDLIB.md` §4.12 is the summary; this file is the reasoning. ## 1. What contests ask Flow problems are modelling problems. The algorithm is a black box the contestant trusts; the work is the network, and the bugs are in the network (node numbering, a missed reverse arc, a cut read from the wrong side, an overflowing "infinity"). Surveyed sources: | Source | What it ships | |---|---| | AtCoder Library | `mf_graph` (Dinic: `add_edge`, `flow(s, t, limit)`, `min_cut(s)`, `get_edge`, `change_edge`), `mcf_graph` (successive shortest paths with potentials: `flow`, `slope`). No matching type: matching is "build a flow". | | KACTL | `Dinic`, `PushRelabel`, `EdmondsKarp`, `MinCostMaxFlow`, `GlobalMinCut` (Stoer–Wagner), `GomoryHu`, `hopcroftKarp`, `DFSMatching`, `MinimumVertexCover`, `WeightedMatching` (Hungarian, rectangular `n <= m`), `GeneralMatching` (randomized Tutte matrix), `MatroidIntersection`. | | ecnerwala (`proto/ports/ecnerwala/*_orig.cpp`) | `cf2147h`: Dinic plus Gusfield's Gomory–Hu loop written inline; `cf2062g`: an O(n^3) Hungarian minimizing Manhattan cost. No other flow code in the 200+ originals. | | Corpus ports | `scout_batch_15`: `dmopc20c7p5` and `noi09p4` (project selection by min cut), `sdoi17r1p4` (Hungarian inside a fractional binary search), `flow_ext.cp` (min-cost flow and Hungarian prototypes); `scout_batch_5/noi06p4` (project selection, hand-offset node numbering); `examples/local-lib/graph/` (Hopcroft–Karp with König cover, min-cost flow, lower-bound flows). | | Codeforces / AtCoder / ICPC usage | Max flow with a modelled network is the dominant shape (assignment with capacities, vertex splitting, grid colourings, project selection); bipartite matching with König's theorem second (vertex cover, independent set, DAG path cover); assignment (Hungarian) and min-cost flow (transport, k disjoint cheapest paths, convex costs by unit arcs) third; lower bounds, Gomory–Hu, global min cut and general matching are rare but recurring at Div. 1 / WF level. | The patterns, in order of frequency, and what each needs from the library: 1. **Max flow on a modelled network.** Arc handles to read flows back, unbounded arcs that never overflow, and node spaces built from several domains plus a source and a sink. 2. **Min cut recovery.** The source side, and which arcs cross it. 3. **Project selection / maximum-weight closure.** Profits, "taking u forces v", answer and chosen set. Three corpus ports hand-build it. 4. **Bipartite matching.** Size, both directions of the matching, König cover; independent set and DAG path cover follow in one line. 5. **Assignment.** Minimum and maximum weight perfect matching on a possibly rectangular cost table, both directions named. 6. **Min-cost flow.** Flow and cost, negative arc costs, a flow limit, and the convex cost curve (`slope`) for "best cost for each k". 7. **Lower bounds.** Feasible circulation, max and min flow with `lo <= f <= hi` per arc. 8. **All-pairs min cut.** Gomory–Hu tree. 9. **General matching.** Maximum cardinality matching in a non-bipartite graph. Deliberately not here yet (section 7): matroid intersection, push–relabel, dynamic capacity changes. ## 2. The API One module, `std.flow`. Two network types that share `Arc`, and free functions for everything whose input is a table or an edge list. ```cp struct Arc(id: 0..2_147_483_648) @get fn rev(self) -> Arc // O(1) struct FlowGraph // Dinic fn new() -> FlowGraph // O(V) fn add(mut self, u: V, v: V, cap: ?Int) -> Arc // O(1); none: never cut fn add_both(mut self, u: V, v: V, cap: Int) -> Arc // O(1); undirected fn flow(self, a: Arc) -> Int // O(1) fn cap(self, a: Arc) -> Int // O(1) fn source(self, a: Arc) -> V // O(1) fn target(self, a: Arc) -> V // O(1) fn max_flow(mut self, s: V, t: V, limit: ?Int = None) -> Int // O(V^2 E); O(E sqrt V) on unit networks fn push_relabel(mut self, s: V, t: V) -> Int // the same flow, O(V^2 sqrt E); highest label, gap fn min_cut(self, s: V) -> [V]Bool // O(V + E) fn reset(mut self) // O(E) struct CostFlow // successive shortest paths fn new() -> CostFlow // O(V) fn add(mut self, u: V, v: V, cap: ?Int, cost: Int) -> Arc // O(1) fn flow(self, a: Arc) -> Int // O(1) fn cap(self, a: Arc) -> Int fn cost(self, a: Arc) -> Int fn source(self, a: Arc) -> V fn target(self, a: Arc) -> V fn min_cost_flow(mut self, s: V, t: V, limit: ?Int = None) -> (flow: Int, cost: Int) // O(F E log V) with potentials, plus O(V E) once if a cost is negative fn slope(mut self, s: V, t: V, limit: ?Int = None) -> List<(flow: Int, cost: Int)> // same cost fn max_closure>(before: G, profit: V -> Int) -> (value: Int, take: [V]Bool) // one max flow on V + 2 fn max_matching(adj: [L]List) -> (size: Int, mate: [L]?R, back: [R]?L) // O(E sqrt V) Hopcroft–Karp fn min_vertex_cover(adj: [L]List) -> (left: [L]Bool, right: [R]Bool) // O(E sqrt V), König fn max_weight_matching(weight: (L, R) -> Int) -> (total: Int, mate: [L]R) // O(L^2 R) Hungarian, L <= R fn min_weight_matching(weight: (L, R) -> Int) -> (total: Int, mate: [L]R) // O(L^2 R) Hungarian, L <= R fn general_matching(adj: [V]List) -> (size: Int, mate: [V]?V) // O(V^3) Edmonds' blossoms fn max_weight_general_matching(edges: [E](u: V, v: V, w: Int)) -> (total: Int, mate: [V]?V) // O(V^3) weighted blossoms, O(V^2) memory fn circulation(arcs: [E](u: V, v: V, lo: Int, hi: Int)) -> ?[E]Int fn max_bounded_flow(arcs: [E](u: V, v: V, lo: Int, hi: Int), s: V, t: V) -> ?(value: Int, flow: [E]Int) fn min_bounded_flow(arcs: [E](u: V, v: V, lo: Int, hi: Int), s: V, t: V) -> ?(value: Int, flow: [E]Int) // each: two max flows on V + 2, Dinic's bound fn gomory_hu(edges: [E](u: V, v: V, w: Int)) -> List<(u: V, v: V, w: Int)> // V - 1 max flows (Gusfield) fn global_min_cut(edges: [E](u: V, v: V, w: Int)) -> (w: Int, side: [V]Bool) // Stoer-Wagner, O(V^3), O(V^2) memory ``` ### Names - **Objective first, then the object:** `max_flow`, `min_cut`, `min_cost_flow`, `max_closure`, `max_matching`, `max_weight_matching` / `min_weight_matching`, `max_bounded_flow` / `min_bounded_flow`, `min_vertex_cover`. A contestant who knows one name guesses the rest. The objective is never encoded by negating weights: `cf2062g` minimized by `max_weight_matching(-cost)` and read `-total` back; the friction report names this. - **Named algorithms where the algorithm is the contract:** `gomory_hu` (the tree it returns is Gomory–Hu's, not any cut tree), `general_matching` (the problem; Edmonds is documented as the algorithm), `circulation`. - **Arc accessors are one vocabulary across both networks:** `flow`, `cap`, `source`, `target`, `rev`; `CostFlow` adds `cost`. `CostFlow.flow(a)` is the arc's flow, so the solver is `min_cost_flow`, not `flow(s, t)` (the earlier §4.12 sketch); one name, one meaning. - **Options are named arguments:** `limit:` on every solver, `cap: None` for an unbounded arc. No `_with_limit`, `_inf` or `_by` variants. ### Why two network types and free functions `FlowGraph` and `CostFlow` are separate because their arcs carry different data and their solvers different contracts; a cost of zero is not a max-flow network (SSP is O(F) augmentations, Dinic is not). They share `Arc` and the accessor names so moving a model from one to the other is a type change and an extra argument per `add`. Matching, assignment, closure, bounded flows and Gomory–Hu are functions because their inputs are values the contestant already has (an adjacency array, a weight function, an edge table read from input), and their result is a value. None of them is incremental in contest use. Each builds a `FlowGraph` internally where it is a flow reduction; the contestant who needs the network itself (to add an arc, to read a residual) writes the reduction with `FlowGraph`, which is ten lines, not a rewrite. ## 3. Laws Every test in `stdlib/flow.cp` checks one of these, most against a brute force on random small inputs. - **Capacity and conservation.** After `max_flow(s, t)`, for every arc, `0 <= g.flow(a) <= g.cap(a)` and `g.flow(a.rev) == -g.flow(a)`; the net flow into every vertex but `s` and `t` is zero. - **Accumulation.** `max_flow` adds to the flow already there and returns the amount added; a second call returns 0. `limit:` stops at that amount; `max_flow(s, t, limit: k) == min(k, max_flow(s, t))`. - **Max-flow min-cut.** After `max_flow(s, t)` without a limit, `let side = g.min_cut(s)` has `side[s]`, `not side[t]`, and the capacities of arcs from `side` to its complement sum to the flow. `min_cut(s)` traps unless such a `max_flow` from `s` came since the last `add` or `reset`, so a stale or partial cut cannot be read. - **No `min_cut(s, t)`.** A combined call returning `(value, side)` was considered and rejected: no corpus port reads the side of an s-t cut (cf1404e, dmopc20c7p5 and noi06p4 print the value; the closure ports use `max_closure`), and the cut value under a second name would be two ways to ask `max_flow` one question. `max_flow` then `min_cut(s)` stays the one spelling; revisit when two ports read the side. - **Unbounded arcs.** `cap: None` is 2^60: no finite cut chooses it, and a sum of 2^3 of them cannot overflow 63 bits. Finite capacities and their total stay below 2^60; the library asserts each `cap >= 0`. - **Closure.** `max_closure(before, profit)` returns `take` closed under `before` (an arc `u -> v` means `take[v]` implies `take[u]`, the direction `peel` reads) and maximizing `sum(profit(v) for v if take[v])`, which equals `value`; the empty set is always feasible, so `value >= 0`. - **König.** `max_matching(adj).size` equals the number of `true`s in `min_vertex_cover(adj)`, and every edge has a covered endpoint. `mate` and `back` are inverse partial maps; every matched pair is an edge. - **Assignment.** `mate` is injective and total on `L`; `total` is the sum of `weight(l, mate[l])`, optimal among all injections `L -> R`; `L.K <= R.K` is asserted. `min_weight_matching(w).total == -max_weight_matching((l, r) => -w(l, r)).total`. - **Min-cost flow.** `min_cost_flow` returns the largest flow up to `limit` and, among flows of that value, the cheapest, provided the network has no negative-cost cycle (asserted only in debug builds by the initial Bellman–Ford). `slope` lists the breakpoints of the convex piecewise-linear cost-of-flow function, from `(0, 0)` to the final `(flow, cost)`; slopes are nondecreasing. - **Bounds.** A returned `flow` has `lo <= flow[e] <= hi` on every arc and conserves at every vertex (for `circulation`) or every vertex but `s` and `t` (bounded flows), and `value` is the net flow out of `s`. `None` means no feasible flow exists. - **Gomory–Hu.** The result is a tree on `V` (`V.K - 1` edges, connected; components of the input are joined by `w = 0` edges), and for every `s != t` the minimum `s-t` cut of the input equals the minimum `w` on the tree path from `s` to `t`. - **General matching.** `mate` is an involution on matched vertices, every matched pair is an edge, and `size` is maximum (no augmenting path). ## 4. Domains and index spaces - **Vertices are a domain parameter.** `FlowGraph`, `CostFlow` and every function are generic over the vertex domain, so a capacity array is `[V]Int`, a cut is `[V]Bool`, and passing an `Item` where a `Node` is expected does not type-check. - **Bipartite sides are two domains.** `max_matching` and the Hungarian take two domains and return `[L]?R` and `[R]?L`; there is no `n + j` numbering of the right side, the classic bug of copying a matching out of a flow network. - **Edges are a domain when the input gives them.** Bounded flows and Gomory–Hu take `[E](u: V, v: V, ...)`, the shape `read` produces and `Graph` already uses, and bounded flows return `[E]Int`: the flow on arc `e` is `flow[e]`, never `flow[i]` with `i` an index into a list built in a different order. - **Arcs are handles, not a domain.** A network grows while it is built, so `Arc` is a typed handle like `Dsu` roots: returned by `add`, valid forever, meaningless across networks. - **Node spaces made of several domains.** The modelled network is usually `Item + Pair + {S, T}` or `Left + Right + {S, T}`. Today a port flattens it into `domain Node = 0..n + m + 2` and writes `Node(n + e.to_idx)` (`noi06p4` calls this friction K11; `dmopc20c7p5`, `noi09p4` repeat it). The fix is the sum domain of spec §21.11, `domain Node = Item + Pair + labels("S", "T")` with `Node(i)` injecting and `Node.S` naming the extra positions. It is a core feature (`domain A + B` is a type error today), so it belongs to the core-extensions lane; `std.flow` needs nothing special from it, because every API here is generic over `V`. Until it lands, the library removes the most common reason for the flattening: `max_closure`, bounded flows and the matchings build their own source and sink inside a fresh domain, so the contestant's node space is only their own domains. ## 5. What stays user code - **The model.** Which arcs, which capacities, vertex splitting, layered time-expanded graphs: this is the problem. The library makes it cheap to write (typed nodes, handles, unbounded arcs) and does not guess it. - **Corollaries that are one line from a result:** maximum independent set (complement of `min_vertex_cover`), minimum DAG path cover (`V.K - max_matching(...).size`), the cut arcs (`arcs.filter(a => side[g.source(a)] and not side[g.target(a)])`), the min cut between `s` and `t` from a Gomory–Hu tree (a path minimum). - **Fractional programming around a solver** (`sdoi17r1p4`): a binary search over a weight function the solver takes as a closure. - **Problem-specific structure on top of a cut** (`cf2147h`'s Gallai parity split): the library gives the tree; the parity argument is the idea. ## 6. Exemplars Real problems written against the API. The ports under `proto/ports/` that these replace are noted; sum domains (section 4) are the one feature used here that the core does not have yet. ### cf2147h: H. Maxflow GCD Coloring ```cp // The gcd of all pairwise max flows is the gcd of the Gomory–Hu tree's // weights. If it is not 1, one colour; otherwise Gallai's parity split. @!multitest domain V = read(1..=50) let m: 0..=choose2(V.count) = read() let edges = read<[m](u: V, v: V, w: 1..=1e6)>() if gcd(gomory_hu(edges).map(e => e.w)) != 1: return answer([V.all]) // ... even_split as in design/EXEMPLARS-PORTS.md ``` The port reimplemented Gusfield: a parent array, `n - 1` resets, a `max_flow`, a `min_cut` read and the re-parenting loop. The idea is "gcd of all pairwise max flows equals the gcd of the cut tree's weights"; the line says it. ### cf2062g: G. Permutation Factory ```cp // Half the minimum Manhattan matching between points (i, p[i]) and // (j, q[j]) is a lower bound and is achieved by sorting in two stages. let (_, mate) = min_weight_matching((i, j) => i.dist(j) + p[i].dist(q[j])) ``` The objective is a minimum; it is written as one. The port negated every weight into `max_weight_matching` and repeated `.ord` subtraction for the distances; `dist` is the domain distance of spec §21. ### DMOPC '20 C7 P5 (project selection) ```cp // Take every reward; forfeit a pair or buy both its items. Max closure. with io(base: 1) domain Item = read(1..=5000) domain Pair = read(0..=5000) let cost: [Item]0..=1e9 = read() let pairs: [Pair](u: Item, v: Item, w: 0..=1e9) = read() domain Node = Item + Pair fn profit(v: Node) -> Int = match v: Item(i) => -cost[i], Pair(e) => pairs[e].w let needs = Graph.directed([(u: Node(i), v: Node(e)) for e in Pair for i in [pairs[e].u, pairs[e].v]]) print(max_closure(before: needs, profit: profit).value) ``` The port flattened `Item + Pair + Src + Snk` into `0..n + m + 2`, wrote the source and sink arcs, and printed `total_reward - max_flow`: the textbook reduction, re-derived. `max_closure` names it, and its `take` answers the "which projects" variant with no second pass over the residual graph. `noi06p4` and `noi09p4` are the same shape. ### cf863F: F. Almost Permutation (convex costs) ```cp // Each position takes one value in [lo, hi]; the k-th use of a value costs // 2k - 1, so total cost is sum cnt^2. Min-cost flow of n units. domain Pos = read(1..=50) domain Val = 1..=Pos.count var lo: [Pos]Val = Val.first var hi: [Pos]Val = Val.last for _ in 0..read<0..=100>(): let (t, l, r, v) = read<(1..=2, Pos, Pos, Val)>() for x in l..=r: if t == 1: lo[x] = max(lo[x], v) else: hi[x] = min(hi[x], v) domain Node = Pos + Val + labels("S", "T") var net = CostFlow() for x in Pos: net.add(Node.S, Node(x), 1, cost: 0) for v in lo[x]..=hi[x]: net.add(Node(x), Node(v), 1, cost: 0) for v in Val: for k in 1..=Pos.count: net.add(Node(v), Node.T, 1, cost: 2 * k - 1) let (flow, cost) = net.min_cost_flow(Node.S, Node.T) print(if flow == Pos.count: cost else: -1) ``` Convex costs as unit arcs of increasing cost is the standard trick; it is user code because it is the model. ### SDOI 2017 Ball Dance (assignment inside a binary search) ```cp // sum a / sum b >= r iff the best assignment of a - r b is >= 0. let ok = r => max_weight_matching((i, j) => a[i][j] * SCALE - r * b[i][j]).total >= 0 print(partition_point(0..=hi, ok) - 1) ``` The solver takes the weight as a closure, so the search re-solves without building a matrix per probe. ## 7. The maximal version The whole area, in the order the corpus is likely to want it: 1. **Sum domains** (core lane): network nodes as `Item + Pair + labels(...)`. The largest single friction in the area. 2. **`global_min_cut(edges)`** (Stoer–Wagner, O(V^3)) next to `gomory_hu`. Shipped: the dense form, since a global cut problem has small `V`. 3. **`max_weight_general_matching`** (Edmonds weighted, O(V^3)): shipped, dense, like `global_min_cut`. Still open: `max_weight_matching` over sparse edges (min-cost flow on unit arcs). 4. **`min_cost_circulation`** with negative cycles (cycle cancelling or cost scaling), and `min_cost_flow` over bounded arcs. 5. **Dynamic networks:** `set_cap(a, c)` with re-flow from the current flow, as ACL's `change_edge`; incremental bipartite matching. 6. ~~Push-relabel as a named second max-flow solver~~: landed as `FlowGraph.push_relabel(s, t)` (decision 112). On cf1404e's 200 x 200 all-`#` grid the port takes 24.5 ms (Dinic: 442 ms; the original: 17 ms). Its solve is 1.02x matched C++ (`bench/flow/prgrid`). 7. **Matroid intersection** and **bipartite edge colouring** (KACTL). 8. **Tooling:** `cpl explain` for a network (vertex and arc counts, the bound the solver will meet), and a trace view of a min cut over the user's own domains. --- # Standard library design: std.geometry URL: /docs/ref/lib/geometry Normative text from [spec/lib/geometry.md](https://github.com/ryanbai1412/cp-lang/blob/main/spec/lib/geometry.md). > **0.3.0 status.** This chapter is the family's design survey and API. > Where it disagrees with the core chapters or the aligned rounds, they > win: `core/03-numbers-layout.md` (four number types, no `I32`/`U32`, > `Mod

` not `Mint`), `core/05-ownership.md` (constructors own their > results), `core/07-sequences.md` (capabilities, views keep keys), > `lib/ops-ranges.md` (`Op`/`Monoid`/laws, `each(...)`, no > `RangeFenwick`, `MinHeap`/`MaxHeap` as `Heap(by:)`) and > `lib/sequence-patterns.md`. The stubs in `std/` are the signatures of > record. Reconciliation of this text is tracked in `delta/`. Status: design for `plan/STDLIB.md` section 4.14. Covers 2D competitive- programming geometry: exact integer points and vectors, orientation, angular sorting, segments, convex hulls and Minkowski sums, polygon area and containment, rotating calipers, closest pair, half-plane intersection, and careful floating-point geometry. ## 1. Contest survey Across Codeforces Div. 1, AtCoder Grand/Regular, and ICPC regionals and World Finals, geometry splits sharply into two worlds: - **Exact integer geometry** (~80% of contest geometry). Input coordinates are integers in `-1e9..=1e9` (occasionally up to `1e18` after prefix sums or DP transitions). Every predicate is a sign of a dot or cross product; floating point is never touched until the final `sqrt` or `atan2`. - **Careful floating-point geometry** (~20% of contest geometry). Constructive tasks (`cf2138f`), reflections (`etsr23r3p2`), line/circle intersections, polygon clipping, and half-plane intersection. Every comparison needs an explicit tolerance `eps`, and exact `==` is a bug. Reference libraries surveyed: - **AtCoder Library (ACL)** deliberately omits geometry, which is why every contestant maintains a personal template. - **KACTL (`content/geometry/`)** is the ICPC gold standard: `Point`, `onSegment`, `segInter`, `inPolygon`, `polygonArea2`, `convexHull`, `hullDiameter`, `inHull`, `closestPair`, `lineInter`, `polygonCut`, `circleLine`, `circleInter`, `circumCircle`, and `halfPlaneInter`. - **ecnerwala's `Point`** (`proto/ports/ecnerwala/cf2138f_orig.cpp`, `ucup4s25e_orig.cpp`, `ucup5s05e_orig.cpp`, `ucup5s05b_orig.cpp`) adds three high-value patterns that KACTL lacks: a wider `AreaT` for cross/dot products, exact integer unit directions (`int_unit` via `gcd`), and arbitrary-base angular ordering (`angle_less(base, s, t)` for `[base, base + 2*pi)`). - **CP Lang corpus and frictions**: - `ucup4s25e.cp` hand-rolls `Pt`, `upper_hull`, and Minkowski sum of two upper chains in O(n) on already-sorted points. - `ucup5s05e.cp` hand-rolls lower and upper hulls *keeping collinear points* while preserving original point IDs. - `cf2138f.cp` (`research/frictions/cf2138f.md`) hand-rolls a `F64` vector type `V` with `len`, `Add`, `Sub`, and scalar `times`/`over`. - `etsr23r3p2.cp` asks for `F64` points and `reflect(p, a, b)`. - `dmopc20c7p2.cp` (`research/ugly-code-friction-audit-3.md` section 9) needs `Pt` to have lexicographic `Ord`, `Hash`, `Read`, and `Show` (`x y`). - `cheerio1s3.cp` uses `Pt` and `cross` for an exact slope sweep. ## 2. Design principles **Two point types: `Pt` (exact `Int`) and `Vec` (careful `F64`).** Exact integer geometry and approximate floating-point geometry do not share safe operations. `Pt` has exact equality, lexicographic `Ord`, `Hash`, `Show` (`"x y"`), exact `norm2 -> Int`, `unit_dir`, and epsilon-free predicates. `Vec` has `unit`, `scale`, `div`, `project`, `reflect`, and epsilon-parameterized predicates, and intentionally omits `Show` because CP Lang forbids printing floats without an explicit precision (`"{v.x:.9f} {v.y:.9f}"`, decision 1.5). Keeping them separate prevents accidental float contamination of exact predicates while letting `Pt` remain non-generic in `std.prelude`. Bridging is one explicit getter: `p.to_vec`. **Overflow-free orientation predicates via `I128`.** With coordinates up to `1e9`, `b - a` reaches `2e9` and `cross(b - a, c - a)` reaches `8e18`, right below `Int.MAX` (`9.22e18`); prefix sums (`ucup4s25e`) or `2e9` grids overflow 64-bit `cross` silently in release builds. `dot` and `cross` return `Int` for ergonomics (since callers add and store them as `Int`), while `dot128` and `cross128` return `I128`. Every orientation predicate (`turn`, `ByAngle`, `ByAngleFrom`, `angle_less`, `same_dir`, `on_segment`, `segments_meet`, `locate`, `locate_convex`, `convex_hull`, `lower_hull`, `upper_hull`, `minkowski_sum`, `minkowski_upper`, `hull_extreme`) computes its cross and dot signs in `I128`, so predicates stay exact for coordinates up to `1e18` at essentially zero cost (`imul` 64x64->128 on x86_64). **Options as named arguments.** Following `plan/STDLIB.md` section 2: - `segments_meet(a, b, c, d, strict: Bool = false)` instead of two functions. - `convex_hull(pts, collinear: Bool = false)` (and `lower_hull`, `upper_hull`, `convex_hull_idx`) instead of `_collinear` twins. - `half_plane_intersect(planes, eps: F64 = 1e-9)` and float predicates take `eps: F64 = 1e-9` as a named default argument. **Shared method vocabulary across `Pt` and `Vec`.** Both `Pt` and `Vec` provide `.norm2`, `.len`, `.perp`, `.perp_cw`, `.angle`, `.dot(o)`, `.cross(o)`, `.dist2(o)`, and `.dist(o)`. Free functions `dot`, `cross`, `dist2`, `dist`, `turn` remain for `Pt` so mathematical notation like `cross(b - a, c - a)` and `turn(a, b, c)` reads naturally. **Domains and index spaces.** Functions over a `List` return `List` or `Int` positions; functions over a domain-indexed `[D]Pt` return `D` handles so callers never lose point IDs or build `(p: Pt, id: Int)` wrapper structs: - `convex_hull_idx(pts: [D]Pt, collinear: Bool = false) -> List` - `closest_pair(pts: [D]Pt) -> (a: D, b: D, dist2: Int)` ## 3. Complete API surface ### 3.1 Exact integer points and vectors ```cp struct Pt(x: Int, y: Int) // Add, Sub, Neg, Eq, Ord (x, y), Hash, Read, Show ("x y") @get fn norm2(self) -> Int // O(1); x*x + y*y @get fn len(self) -> F64 // O(1); sqrt(F64(norm2)) @get fn perp(self) -> Pt // O(1); 90 deg CCW: Pt(-y, x) @get fn perp_cw(self) -> Pt // O(1); 90 deg CW: Pt(y, -x) @get fn angle(self) -> F64 // O(1); atan2(y, x) in [-pi, pi] @get fn unit_dir(self) -> Pt // O(log min(|x|, |y|)); reduced by gcd, Pt(0, 0) for zero @get fn to_vec(self) -> Vec // O(1); Vec(F64(x), F64(y)) fn scale(self, k: Int) -> Pt // O(1); Pt(x * k, y * k) fn dot(self, o: Pt) -> Int // O(1) fn cross(self, o: Pt) -> Int // O(1) fn dist2(self, o: Pt) -> Int // O(1) fn dist(self, o: Pt) -> F64 // O(1) fn dot(a: Pt, b: Pt) -> Int // O(1); safe for |coords| <= 2e9 fn cross(a: Pt, b: Pt) -> Int // O(1); safe for |coords| <= 2e9 fn dot128(a: Pt, b: Pt) -> I128 // O(1); safe for all Int fn cross128(a: Pt, b: Pt) -> I128 // O(1); safe for all Int fn dist2(a: Pt, b: Pt) -> Int // O(1); (a - b).norm2 fn dist(a: Pt, b: Pt) -> F64 // O(1); (a - b).len fn manhattan(a: Pt, b: Pt) -> Int // O(1); |a.x - b.x| + |a.y - b.y| fn turn(a: Pt, b: Pt, c: Pt) -> Int // O(1), I128; 1 CCW, -1 CW, 0 collinear fn same_dir(a: Pt, b: Pt) -> Bool // O(1), I128; parallel and same ray ``` ### 3.2 Angular sorting ```cp struct ByAngle(p: Pt) // Ord: CCW in [0, 2*pi) from +x; zero first; I128 struct ByAngleFrom(base: Pt, p: Pt) // Ord: CCW in [base, base + 2*pi); zero first; I128 fn angle_less(base: Pt, a: Pt, b: Pt) -> Bool // O(1), I128; a precedes b CCW from base ``` `ByAngle` works directly with `sort(mut dirs, by: ByAngle)` and around an origin via `sort(mut pts, by: p => ByAngle(p - o))`. `ByAngleFrom(base, p)` orders directions starting from any non-zero ray `base` without splitting or wrapping the array twice. ### 3.3 Segments ```cp fn on_segment(p: Pt, a: Pt, b: Pt) -> Bool // O(1), I128; true iff p lies on the closed segment [a, b] fn segments_meet(a: Pt, b: Pt, c: Pt, d: Pt, strict: Bool = false) -> Bool // O(1), I128; closed segments share a point, or proper interior crossing when strict: true ``` ### 3.4 Convex hulls, chains, and Minkowski sums ```cp fn lower_hull(pts: List, collinear: Bool = false) -> List // O(n) time, O(n) space; precondition: pts sorted by (x, y); lower chain left-to-right fn upper_hull(pts: List, collinear: Bool = false) -> List // O(n) time, O(n) space; precondition: pts sorted by (x, y); upper chain left-to-right fn convex_hull(pts: List, collinear: Bool = false) -> List // O(n log n) time, O(n) space; CCW from lowest-leftmost point, deduplicated fn convex_hull_idx(pts: [D]Pt, collinear: Bool = false) -> List // O(n log n) time, O(n) space; CCW hull vertices as D handles fn minkowski_sum(a: List, b: List) -> List // O(|a| + |b|); CCW convex hull of {p + q : p in a, q in b} for non-empty CCW hulls a, b fn minkowski_upper(a: List, b: List) -> List // O(|a| + |b|); upper convex chain of {p + q} for non-empty left-to-right upper chains a, b ``` Keeping `lower_hull` and `upper_hull` O(n) on already x-sorted inputs is essential for O(n log n) divide-and-conquer hulls (such as `ucup4s25e`). `convex_hull` sorts, deduplicates, and stitches the two chains. ### 3.5 Polygons and rotating calipers ```cp fn area2(poly: List) -> Int // O(n); twice signed area (+ CCW, - CW) enum Location = Inside | Boundary | Outside fn locate(poly: List, p: Pt) -> Location // O(n), I128; simple polygon (either winding) fn locate_convex(hull: List, p: Pt) -> Location // O(log n), I128; CCW convex polygon (no 3 collinear) fn diameter2(hull: List) -> Int // O(n), I128; max squared distance on a CCW convex hull (0 for < 2 points) fn hull_extreme(hull: List, dir: Pt) -> Int // O(log n), I128; index in 0..hull.len maximizing dot(hull[i], dir) on a CCW hull fn hull_tangents(hull: List, p: Pt) -> (left: Int, right: Int) // O(log n), I128; tangent vertex indices from strictly outside point p to CCW hull fn min_bounding_box(hull: List) -> (area: F64, perimeter: F64) // O(n), I128 calipers; minimum-area and minimum-perimeter enclosing rectangle of a CCW hull ``` ### 3.6 Closest pair ```cp fn closest_pair2(pts: List) -> Int // O(n log n) time, O(n) space; min squared distance among pts (requires pts.len >= 2) fn closest_pair(pts: [D]Pt) -> (a: D, b: D, dist2: Int) // O(n log n) time, O(n) space; closest distinct pair of D handles and squared distance ``` ### 3.7 Careful floating-point geometry and half-plane intersection ```cp const PI: F64 = 3.14159265358979323846 fn close(a: F64, b: F64, eps: F64 = 1e-9) -> Bool // O(1); |a - b| <= eps fn sign_eps(x: F64, eps: F64 = 1e-9) -> Int // O(1); 1, 0, or -1 with tolerance eps struct Vec(x: F64, y: F64) // Add, Sub, Neg; intentionally no Show @get fn norm2(self) -> F64 // O(1) @get fn len(self) -> F64 // O(1) @get fn unit(self) -> Vec // O(1); traps if len == 0 @get fn perp(self) -> Vec // O(1); Vec(-y, x) @get fn perp_cw(self) -> Vec // O(1); Vec(y, -x) @get fn angle(self) -> F64 // O(1); atan2(y, x) in [-pi, pi] fn scale(self, k: F64) -> Vec // O(1); Vec(x * k, y * k) fn div(self, k: F64) -> Vec // O(1); Vec(x / k, y / k) fn dot(self, o: Vec) -> F64 // O(1) fn cross(self, o: Vec) -> F64 // O(1) fn dist2(self, o: Vec) -> F64 // O(1) fn dist(self, o: Vec) -> F64 // O(1) fn rot(self, by: Vec) -> Vec // O(1); rotate by unit vector `by` fn polygon_area(poly: List) -> F64 // O(n); signed area (+ CCW, - CW) fn project(p: Vec, a: Vec, b: Vec) -> Vec // O(1); orthogonal projection onto line ab fn reflect(p: Vec, a: Vec, b: Vec) -> Vec // O(1); reflection across line ab fn line_dist(p: Vec, a: Vec, b: Vec) -> F64 // O(1); perpendicular distance from p to line ab fn seg_dist(p: Vec, a: Vec, b: Vec, eps: F64 = 1e-9) -> F64 // O(1); distance from p to segment [a, b] fn line_intersect(a: Vec, b: Vec, c: Vec, d: Vec, eps: F64 = 1e-9) -> ?Vec // O(1); intersection of lines ab and cd, None if parallel fn polygon_cut(poly: List, a: Vec, b: Vec, eps: F64 = 1e-9) -> List // O(n); Sutherland-Hodgman clip to left half-plane of directed line a -> b fn circle_line_intersect(c: Vec, r: F64, a: Vec, b: Vec, eps: F64 = 1e-9) -> List // O(1); 0, 1, or 2 intersection points of circle (c, r) with line ab fn circle_intersect(c1: Vec, r1: F64, c2: Vec, r2: F64, eps: F64 = 1e-9) -> List // O(1); 0, 1, or 2 intersection points of two circles fn circle_tangents(center: Vec, r: F64, p: Vec, eps: F64 = 1e-9) -> List // O(1); 0, 1, or 2 tangent points from p to circle (center, r) fn circle_circle_tangents(c1: Vec, r1: F64, c2: Vec, r2: F64, inner: Bool = false, eps: F64 = 1e-9) -> List<(Vec, Vec)> // O(1); 0, 1, or 2 outer (or inner when inner: true) common tangent segments (on c1, on c2) fn circles_union_area(circles: List<(c: Vec, r: F64)>, eps: F64 = 1e-9) -> F64 // O(n^2 log n); total area of the union of disks via Green's theorem arc sweep fn circumcenter(a: Vec, b: Vec, c: Vec, eps: F64 = 1e-9) -> ?Vec // O(1); circumcenter of triangle abc, None if collinear struct HalfPlane(p: Vec, dir: Vec) // left side of ray p + t*dir (t in R) fn through(a: Vec, b: Vec) -> HalfPlane // O(1); keep left of a -> b fn from_line(a: F64, b: F64, c: F64) -> HalfPlane // O(1); keep a*x + b*y + c >= 0 fn side(self, q: Vec) -> F64 // O(1); dir.cross(q - p) fn half_plane_intersect(planes: List, eps: F64 = 1e-9) -> List // O(n log n) time, O(n) space; CCW vertices of bounded intersection (empty if empty). // Add a bounding box of four half-planes if the region may be unbounded. ``` ## 4. Laws and invariants Every implementation test verifies these laws on random and degenerate inputs: - **Vector algebra**: `dot(a, b) == dot(b, a)`, `cross(a, b) == -cross(b, a)`, `dot(a, a.perp) == 0`, `cross(a, a.perp) == a.norm2`, `a.perp.perp == -a`, `turn(a, b, c) == -turn(a, c, b)`. - **Order**: `ByAngle` and `ByAngleFrom(base, _)` are strict weak orders (irreflexive, asymmetric, transitive on non-parallel rays). - **Segments**: `segments_meet(a, b, c, d)` is symmetric in `(a, b) <-> (c, d)` and `a <-> b`, and `strict: true` implies `strict: false`. - **Convex hull**: every vertex of `h = convex_hull(pts)` is in `pts`; every consecutive triple turns strictly left (`collinear: false`) or non-right (`collinear: true`); every `p in pts` satisfies `locate(h, p) != Location.Outside`; `area2(h) > 0` for non-collinear inputs and `area2(h.rev) == -area2(h)`. - **Fast convex queries**: `locate_convex(h, p) == locate(h, p)` for all `p` on every random hull `h`; `dot(h[hull_extreme(h, d)], d) == max(dot(v, d) for v in h)`; `diameter2(h) == max(dist2(u, v) for u in h for v in h)`. - **Minkowski sum**: `minkowski_sum(a, b) == convex_hull([p + q for p in a for q in b])`; `minkowski_upper(a, b)` equals the upper hull of pairwise sums. - **Closest pair**: `closest_pair2(pts)` matches O(n^2) brute force, and `closest_pair(pts)` returns distinct `a != b` with `dist2(pts[a], pts[b]) == closest_pair2(...)`. - **Floating point**: `reflect(reflect(p, a, b), a, b)` is `close` to `p`; `project(p, a, b)` lies on `ab` with `(p - proj).dot(b - a)` close to `0`; `half_plane_intersect` agrees with folding `polygon_cut` over a bounding box in signed area and vertex count. ## 5. Core features wanted (non-blocking) Two core features would sharpen `std.geometry` further once the core lane delivers them; neither blocks shipping the full API today: - **Heterogeneous `Mul` and `Div`**: lets `v * k` and `v / k` replace `v.scale(k)` and `v.div(k)` on both `Pt` and `Vec` (filed in `research/frictions/cf2138f.md`). - **`sin` and `cos` intrinsics** (listed in `decisions.md` 1.5): enables `Vec.rot(by: u)` rotates by a unit vector without `sin`/`cos` (avoiding a `_by` twin per §2). ## 6. What stays user code or `examples/local-lib/geom/` - **Dynamic convex hull / Li Chao tree** (DP optimization, already staged in `examples/local-lib/ds/li_chao.cp`). - **3D geometry and 3D convex hull** (rare outside ICPC WF; belongs in `examples/local-lib/geom/`). - **Delaunay triangulation, Voronoi diagrams, and KD-trees** (niche; exact integer incircle is a degree-4 determinant reaching `16e36` for `1e9` coordinates, overflowing `I128` without multi-precision integers). - **General non-convex polygon union area** (rare compared to circle union and convex clipping; user code or `local-lib`). - **Exact homogeneous rational points** (`Hom(x, y, w)` as in `nccc10s4`): specialized to exact line-arrangement graphs; user code or `local-lib`. - **Sweep-line event loops**: problem-specific state transitions stay in user code, built on `Pt`, `turn`, `ByAngle`, and `segments_meet`. ## 7. Real problems written against this API ### Problem 1: UCup 4 Stage 25 (Zagreb) E — Maximum Subarray Sum by Length Divide and conquer on prefix sums `(i, pref[i])`; at each split, combine the upper hull of negated left prefixes with the upper hull of right prefixes via `minkowski_upper`, then answer offline linear queries on the final upper hull. ```cp use std.geometry.{Pt, dot, upper_hull, minkowski_upper} @!multitest let (n, q): (1..=2e5, 1..=2e5) = read() let a: [0..n]Int = read() var pref: [0..=n]Pt = Pt(0, 0) for i in 0..n: pref[i + 1] = Pt(i + 1, pref[i].y + a[i]) var best: [0..n]Pt = [0..n] i => pref[i + 1] fn solve(lo: Int, hi: Int): if hi - lo <= 1: return let md = (lo + hi) / 2 solve(lo, md) solve(md, hi) let left = upper_hull([-pref[i] for i in (lo..md).rev]) let right = upper_hull([pref[i] for i in md..hi]) for p in minkowski_upper(left, right): best[p.x - 1].y max= p.y solve(0, n + 1) let hull = upper_hull([best[i] for i in 0..n]) let qs: [0..q]Int = read() var ans: [0..q]Int = 0 var at = 0 for (v, id) in [(qs[i], i) for i in 0..q].sorted(): let dir = Pt(v, 1) while at + 1 < hull.len and dot(hull[at + 1] - hull[at], dir) >= 0: at += 1 ans[id] = dot(hull[at], dir) print(ans) ``` ### Problem 2: UCup 5 Stage 5 (Chengdu) E — Point in Triangle Keep collinear points on the convex hull using domain handles so every vertex carries its 1-based input index directly without a wrapper struct. ```cp use std.geometry.{Pt, Location, turn, convex_hull_idx, locate_convex} @!multitest let (n, q): (3..=2e5, 1..=2e5) = read() domain Site = 1..=n let pts: [Site]Pt = read() let hull = convex_hull_idx(pts, collinear: true) let off_diag: ?Site = if hull.len == 4: first(s for s in Site if turn(pts[hull[0]], pts[hull[2]], pts[s]) != 0 and turn(pts[hull[1]], pts[hull[3]], pts[s]) != 0) else: None // Split hull into lower/upper x-monotone chains and test the local window. let hull_pts = [pts[s] for s in hull] for _ in 0..q: let c: Pt = read() if locate_convex(hull_pts, c) != Location.Inside: print(-1) continue // Pick candidate vertices around c.x and check triples with turn(...). ``` ### Problem 3: Codeforces 2138 F — Floating-Point Triangle Ladder Uses `Vec` directly instead of defining a local struct and `Add`/`Sub` impls. ```cp use std.geometry.{Vec} fn fits(a: Vec, b: Vec) -> Bool = 0.5 <= a.dist(b) <= 1.0 @!multitest let (p, q, m): (1..=10_000, 1..=10_000, 3..=28_285) = read() let t = Vec(F64(p), F64(q)) let k = m / 2 print(m) var drawn = 2 fn draw(u: Int, v: Int, c: Vec) -> Int: print("{u} {v} {c.x:.20f} {c.y:.20f}") drawn += 1 drawn fn ladder(off: Int, on: Int, from: Int, off_at: Int -> Vec, on_at: Int -> Vec): var (a, b) = (off, on) for i in from..=k: a = draw(a, b, off_at(i)) b = draw(a, b, on_at(i)) let (p1, p2) = (Vec(0.0, 0.0), Vec(1.0, 0.0)) if m % 2 == 0: let d = t / F64(k) let side = Vec(0.5, d.y - 0.5) ladder(2, 1, 1, i => side + d * F64(i - 1), i => d * F64(i)) else: let d = t.unit let (t1, t0) = (t - d * F64(k - 1), t - d * F64(k)) let start = if fits(t0, p2): t0 else: Vec( 0.5 + 0.75 * sqrt(3.0 / 13.0), 0.75 + sqrt(3.0 / 13.0) * 0.5, ) fn side() -> Vec: for x in -64..=64: for y in -64..=64: let c = Vec(F64(x) / 64.0, F64(y) / 64.0) if fits(c, p1) and fits(c, p2) and fits(c, start) and fits(c, t0) and fits(c, t1): return c p1 let s = side() let a = draw(1, 2, s) let b = draw(2, a, start) let c = draw(a, b, t1) ladder(a, c, 2, i => s + d * F64(i - 1), i => t0 + d * F64(i)) ``` ### Problem 4: ETSR 2023 R3 P2 — Paper Folding Unfold backwards across each fold line with `Vec` and `reflect`. ```cp use std.geometry.{Vec, reflect} let n: 1..=10 = read() domain Fold = 1..=n let folds: [Fold](a: Vec, b: Vec) = read() let q: 1..=1e5 = read() fn layers(k: Int, p: Vec) -> Int: if k == 0: return if 0.0 <= p.x <= 100.0 and 0.0 <= p.y <= 100.0: 1 else: 0 let (a, b) = folds[Fold(k)] if (b - a).cross(p - a) < 0.0: return 0 layers(k - 1, p) + layers(k - 1, reflect(p, a, b)) for _ in 0..q: let p: Vec = read() print(layers(n, p)) ``` ### Problem 5: Area of Intersection of Half-Planes Classic ICPC / Library Checker task: given `n` directed half-planes inside `[-B, B]^2`, compute the area of their intersection. ```cp use std.geometry.{Vec, HalfPlane, half_plane_intersect, polygon_area} let n: 1..=2e5 = read() let bound = 1e9 var planes: List = [ HalfPlane.through(Vec(-bound, -bound), Vec(bound, -bound)), HalfPlane.through(Vec(bound, -bound), Vec(bound, bound)), HalfPlane.through(Vec(bound, bound), Vec(-bound, bound)), HalfPlane.through(Vec(-bound, bound), Vec(-bound, -bound)), ] for _ in 0..n: let (a, b): (Vec, Vec) = read() planes.push(HalfPlane.through(a, b)) let poly = half_plane_intersect(planes) print("{polygon_area(poly):.10f}") ``` ## 10. Overflow bounds, Shamos–Hoey, float-free `arg`, and 3D hull ### Coordinate-range overflow table Exact integer geometry is the default path. Coordinate bounds in declarations (e.g. `Pt<-1e9..=1e9>` once parameterized ranged structs land; today documented on `Pt`/`Pt3`) determine which width is overflow-free: | Coordinate bound | Max diff | `dot` / `cross` / `dist2` | `turn` / `cross128` / `dot128` | `any_segments_meet` (`I128`) | `convex_hull_3d` (`I128`) | | --- | --- | --- | --- | --- | --- | | `\|c\| <= 1e6` | `2e6` | `8e12` (`Int` safe) | `8e12` (`I128` safe) | `1.6e19` (`I128` safe) | `4.8e19` (`I128` safe) | | `\|c\| <= 1e9` (`Pt<-1e9..=1e9>`) | `2e9` | `8e18` (2-pt diff fits `Int`; `dot`/`cross` of single vectors <= `2e18`) | `8e18` (`I128` safe, 19 orders spare) | `1.6e28` (`I128` safe) | `4.8e28` (`I128` safe) | | `\|c\| <= 1e12` | `2e12` | overflows `Int` | `8e24` (`I128` safe) | `1.6e37` (`I128` safe) | `4.8e37` (`I128` safe) | | `\|c\| <= 2e18` | `4e18` | overflows `Int` | `3.2e37` (`I128` safe) | overflows `I128` | overflows `I128` | ### Additional exact API - `arg(p: Pt) -> ByAngle` — float-free angular sort key (`sort(mut pts, by: arg)` or `sort(mut pts, by: p => arg(p - base))`). - `any_segments_meet(segs: List<(a: Pt, b: Pt)>, strict: Bool = false) -> ?(Int, Int)` — O(n log n) Shamos–Hoey sweep line using an exact `I128` comparator in a deterministic treap (handles vertical segments, shared endpoints, and both `strict: false` and `strict: true`). - `Pt3(x: Int, y: Int, z: Int)` with `Add`, `Sub`, `Neg`, `Show`, `norm2`, `norm2_128`, `len`, `scale`, `dot3`, `dot3_128`, `cross3`, `dist2_3`, and O(n^2) exact `I128` `convex_hull_3d(pts: List) -> List<(Int, Int, Int)>`. ## Coverage Audit against AtCoder Library (which omits geometry), KACTL (`content/geometry/`), cp-algorithms (Geometry), and top competitors' personal templates (ecnerwala, tourist, benq, jiangly). Each topic is marked **have** (implemented and tested in `stdlib/geometry.cp`), **new** (specified in `plan/STDLIB.md` 4.14 `[new]`), or **out** (excluded with reason). | # | Topic | Status | Surface / Reason | | --- | --- | --- | --- | | 1 | Exact 2D point/vector arithmetic & `I128` predicates | **have** | `Pt`, `norm2`, `norm2_128`, `len`, `perp`, `perp_cw`, `angle`, `unit_dir`, `to_vec`, `dot`, `cross`, `dot128`, `cross128`, `dist2`, `dist2_128`, `dist`, `turn`, `same_dir` | | 2 | Exact angular sorting from `+x` | **have** | `ByAngle`, `arg`, `angle_less` | | 3 | Segment containment & pairwise intersection | **have** | `on_segment(..., strict:)`, `segments_meet(..., strict:)` | | 4 | Any-two-segments intersection (Shamos–Hoey sweep) | **have** | `any_segments_meet(..., strict:)` | | 5 | 2D convex hull & x-monotone chains (batch) | **have** | `lower_hull`, `upper_hull`, `convex_hull`, `convex_hull_idx` | | 6 | Minkowski sum (full & upper chain) | **have** | `minkowski_sum`, `minkowski_upper` | | 7 | Polygon signed area & point location (simple & convex) | **have** | `area2`, `area2_128`, `Location`, `locate`, `locate_convex`, `polygon_area` | | 8 | Rotating calipers (diameter & min bounding box) | **have** | `diameter2`, `min_bounding_box` | | 9 | Convex hull O(log n) queries (extreme & tangents) | **have** | `hull_extreme`, `hull_tangents` | | 10 | Closest pair of points (2D exact) | **have** | `closest_pair2`, `closest_pair` | | 11 | Careful floating-point 2D vectors & lines | **have** | `Vec`, `close`, `sign_eps`, `vdot`, `vcross`, `vdist`, `vturn`, `project`, `reflect`, `line_dist`, `seg_dist`, `line_intersect`, `circumcenter` | | 12 | Circle-line, circle-circle intersections & tangents | **have** | `circle_line_intersect`, `circle_intersect`, `circle_tangents`, `circle_circle_tangents` | | 13 | Circle-polygon intersection area & union of circles | **have** | `circle_polygon_area`, `circles_union_area` | | 14 | Minimum enclosing circle (Welzl) | **have** | `min_enclosing_circle` | | 15 | Half-plane intersection & Sutherland–Hodgman clip | **have** | `HalfPlane`, `half_plane_intersect`, `polygon_cut` | | 16 | 3D exact integer points & 3D convex hull | **have** | `Pt3`, `dot3`, `dot3_128`, `cross3`, `dist2_3`, `convex_hull_3d` | | 17 | L1 / L-infinity metrics & `Pt`/`Vec`/`Pt3` method parity | **new** | `manhattan`, `chebyshev`, `.dot`/`.cross`/`.dist2`/`.dist` on `Pt`, `Vec`, `Pt3`, `Vec.perp_cw`, `Vec.from_angle`, `angle_between`, `PI` | | 18 | Arbitrary-base exact angular sorting | **new** | `ByAngleFrom`, `angle_less(..., from:)` | | 19 | Segment/ray floating-point intersections | **new** | `segment_intersect`, `ray_hits_segment` | | 20 | Domain-indexed segment & half-hull twins | **new** | `any_segments_meet_idx`, `lower_hull_idx`, `upper_hull_idx`, `convex_hull_3d_idx` | | 21 | Online (incremental) 2D convex hull | **new** | `OnlineHull` (`add`, `locate`, `extreme`, `area2`, `len`, `is_empty`, `vertices`, `clear`) | | 22 | Minkowski lower chain & convex polygon overlap/intersection | **new** | `minkowski_lower`, `convex_polygons_overlap`, `convex_polygon_intersect` | | 23 | Convex hull width & O(log n) line-hull intersection | **new** | `hull_width`, `hull_line_intersect` | | 24 | Farthest pair & Manhattan (L1) MST candidates | **new** | `farthest_pair`, `manhattan_mst` | | 25 | Simple polygon centroid, kernel, triangulation & Pick's theorem | **new** | `polygon_centroid`, `polygon_kernel`, `polygon_triangulate`, `pick_interior`, `pick_boundary` | | 26 | First-class `Circle`, incenter, circle-circle area & inversion | **new** | `Circle` (`through`, `area`, `circumference`, `locate`), `incenter`, `circle_circle_area`, `invert` | | 27 | `HalfPlane` factories & optional bounding box | **new** | `HalfPlane.through`, `HalfPlane.from_line`, `HalfPlane.side`, `half_plane_intersect(..., bound:)` | | 28 | Axis-aligned integer rectangles & union area sweep | **new** | `Rect(x: Range, y: Range)`, `rects_union_area` | | 29 | Planar straight-line graph faces & offline point location | **new** | `planar_faces`, `point_location_planar` | | 30 | Exact Delaunay triangulation & Voronoi cells | **new** | `delaunay`, `voronoi_cells` | | 31 | 3D floating-point vectors, planes, polyhedron volume & spherical distance | **new** | `Vec3`, `Plane3`, `line_plane_intersect`, `sphere_dist`, `polyhedron_volume6` | | 32 | 1D convex hull trick / `LineContainer` / `LiChao` | **out** | Owned by `std.dp` (4.16): 1D linear envelopes `k*x + m` are DP optimizations, not 2D geometry. | | 33 | KD-tree / 2D orthogonal range tree | **out** | Problem-specific pruning and monoids belong in `std.ranges` or user code; static 2D sums are `Prefix` / `Fenwick2D`. | | 34 | General non-convex polygon boolean ops (union/diff/intersection) | **out** | Rare in contests and edge-case heavy; `polygon_cut`, `convex_polygon_intersect`, `circles_union_area`, and `rects_union_area` cover contest needs. | | 35 | General 3D mesh boolean ops / CSG / 3D half-space intersection | **out** | Virtually absent from contests; `convex_hull_3d`, `Plane3`, and `polyhedron_volume6` cover 3D contest geometry. | | 36 | Exact homogeneous / rational points (`Hom(x, y, w)`) | **out** | Specialized to exact line-arrangement graphs; belongs in `std.math` (`Frac`) or `examples/local-lib/` rather than duplicating every 2D primitive. | | 37 | Generic sweep-line event framework | **out** | Sweep state transitions are problem-specific; concrete sweeps (`any_segments_meet`, `circles_union_area`, `rects_union_area`, `point_location_planar`) and exact keys (`ByAngle`, `turn`) stay composable. | | 38 | Spatial hashing / quadtrees / BVH | **out** | Heuristic acceleration structures; `closest_pair` and `delaunay` cover exact proximity. | | 39 | Ellipses, Bezier curves, and general conics | **out** | Rare in contests; affine scaling reduces ellipses to circles and ternary search handles general smooth curves. | | 40 | 3D dynamic convex hull / 3D Delaunay / 3D Voronoi | **out** | Outside standard contest scope; O(n^2) static `convex_hull_3d` suffices. | | 41 | Sub-polygon chord-area prefix structure | **out** | Two lines composing `Prefix` over `cross(poly[i], poly[i.next])`; no standalone type needed. | Totals: **16 have**, **15 new**, **10 out** (41 topics). ## Cross-area ### Construction and naming coherence - **Construction convention:** Plain positional constructors `T(...)` for all value types (`Pt(x, y)`, `Pt3(x, y, z)`, `Vec(x, y)`, `Vec3(x, y, z)`, `Circle(c, r)`, `HalfPlane(p, dir)`, `Plane3(n, d)`, `Rect(x, y)`, `ByAngle(p)`, `ByAngleFrom(base, p)`) and empty constructor `OnlineHull()` for stateful structures (matching `Dsu()`, `MinHeap()`, `IntervalMap()` in `plan/STDLIB.md` §2). Alternate representations use named factories (`HalfPlane.through`, `HalfPlane.from_line`, `Circle.through`, `Plane3.through`, `Vec.from_angle`). - **Argument vocabulary:** `strict: Bool = false`, `collinear: Bool = false`, `inner: Bool = false`, `from: Pt = Pt(1, 0)`, `by: Vec`, `bound: ?F64 = none`, `eps: F64 = 1e-9` — no `_by` or `_with` twins. Domain-indexed twins of `List` functions consistently use `_idx` (`convex_hull_idx`, `lower_hull_idx`, `upper_hull_idx`, `any_segments_meet_idx`, `convex_hull_3d_idx`); domain-first functions (`closest_pair`, `farthest_pair`, `manhattan_mst`, `delaunay`, `voronoi_cells`, `planar_faces`) keep the base name. - **Method parity across vector types:** Adding `.dot(o)`, `.cross(o)`, `.dist2(o)`, `.dist(o)` on `Pt`, `Vec`, `Pt3`, and `Vec3` removes the `dot`/`vdot`/`dot3` split at method call sites while preserving short free functions `dot`/`cross`/`turn` for `Pt`. ### Cross-area name boundaries and collisions - **`dist` (`std.geometry` vs `std.tree.Rooted.dist` / `std.graph`):** `std.geometry.dist(a: Pt, b: Pt) -> F64` is a free function (and `.dist(o)` method on `Pt`/`Vec`/`Pt3`/`Vec3`); `Rooted.dist(a: V, b: V) -> Int` is a method on `Rooted`. No collision when `dist` is called as a method or imported explicitly. - **`Line` / convex hull trick (`std.dp` vs `std.geometry`):** `std.dp` (4.16) owns `Line(k, m)` and `LiChao` for 1D linear DP envelopes. `std.geometry` deliberately omits a `Line` struct (using `HalfPlane` or endpoint pairs `(a, b)`) and restricts `OnlineHull` to 2D integer point hulls. - **`PI`, `close`, `sign_eps` (`std.geometry` vs `std.math`):** `PI` belongs canonically in `std.math` (also needed by FFT in `std.ntt`) and is re-exported by `std.geometry` to avoid duplication. `close` and `sign_eps` live in `std.geometry` today; if `std.math` adds floating-point root-finding or ternary search, they should move to `std.math` with re-exports here. - **`Range` (`core` / `std.interval` vs `std.geometry.Rect`):** `Rect(x: Range, y: Range)` reuses core `Range` (and cut-range conversion per decision 124) instead of defining a second interval type. - **`manhattan_mst` and `planar_faces` (`std.geometry` vs `std.graph`):** Owned by `std.geometry` because both are driven by geometric sweeps / angular sorting (`ByAngle`) and return plain edge lists or vertex cycles that compose directly with `std.graph` and `Dsu`. - **`std.prelude` slots:** Only `Pt` and `ByAngle` are in `std.prelude` (2 of 80 slots); all other names require `use std.geometry.{...}`. ## Powers Language powers needed to write the full `std.geometry` spec without special cases or copies: 1. **Trigonometric intrinsics (`sin`, `cos`, `acos`, `asin`)** (`decisions.md` §1.5; today only `atan2` exists). - **Signatures:** `Vec.from_angle(rad: F64) -> Vec`, `Vec3.rot(self, axis: Vec3, rad: F64) -> Vec3`, `sphere_dist(a: Vec3, b: Vec3, r: F64 = 1.0) -> F64`. - **Smallest example:** ```cp let q = v.rot(by: Vec.from_angle(PI / 3.0)) ``` 2. **Protocols with associated types (`Indexed` / `Seq`).** - **Signatures:** Generalizing read-only sequence inputs from `List` / `List` to `S: Indexed` / `S: Indexed` across `area2`, `area2_128`, `locate`, `locate_convex`, `lower_hull`, `upper_hull`, `convex_hull`, `minkowski_sum`, `minkowski_upper`, `minkowski_lower`, `hull_extreme`, `hull_tangents`, `hull_width`, `hull_line_intersect`, `diameter2`, `min_bounding_box`, `closest_pair2`, `polygon_area`, `polygon_cut`, `polygon_centroid`, `polygon_kernel`, `polygon_triangulate`, `circle_polygon_area`, `pick_interior`, `pick_boundary`. - **Smallest example:** ```cp let left = upper_hull(pref[lo..md]) // zero-copy slice of [D]Pt or List ``` 3. **Range-parameterized structs with defaults (`struct Pt(x: R, y: R)`).** - **Signatures:** `Pt`, `Pt3` (packing `Pt<-1e9..=1e9>` into 8 bytes and carrying coordinate bounds for compile-time overflow proofs on `dot`/`cross`/`dist2`). - **Smallest example:** ```cp let p: [V]Pt<1..=100> = read() ``` 4. **Wide multiplication intrinsic (`mulhi` / exact 256-bit sign)** (`plan/STDLIB.md` §3 `[new, core lane]`). - **Signatures:** `delaunay(pts: [D]Pt) -> List<(D, D, D)>`, `voronoi_cells(pts: [D]Pt, bound: F64) -> [D]List` (exact degree-4 `incircle` determinant reaches `1.92e38` for `|coords| <= 1e9`, exceeding `I128.MAX = 1.70e38`). - **Smallest example:** ```cp let tris = delaunay(pts) // exact incircle for |x|, |y| <= 1e9 ``` 5. **Public `Read` protocol (`impl Read for T`).** - **Signatures:** `impl Read for Vec`, `impl Read for Pt3`, `impl Read for Vec3`, `impl Read for Circle`, `impl Read for HalfPlane`, `impl Read for Rect` (today only `Pt` has compiler-assisted `Read`). - **Smallest example:** ```cp let cs: [C]Circle = read() ``` 6. **Half-open cut-range conversion (`Range` -> `Range`, decision 124).** - **Signatures:** `Rect(x: Range, y: Range)` and passing `poly[j..i]` (with `j, i: D.bounds`) into `area2`, `upper_hull`, `lower_hull`, `locate`. - **Smallest example:** ```cp let a = area2(poly[j..i]) ``` 7. **User-defined optional niches (`?Vec`, `?Pt`, `?Circle`, `?Rect`, `?Plane3`).** - **Signatures:** `line_intersect(...) -> ?Vec`, `circumcenter(...) -> ?Vec`, `ray_hits_segment(...) -> ?Vec`, `Circle.through(...) -> ?Circle`, `incenter(...) -> ?Circle`, `Rect.intersect(...) -> ?Rect`, `OnlineHull.extreme(...) -> ?Pt`, `Plane3.through(...) -> ?Plane3`, `line_plane_intersect(...) -> ?Vec3` (avoids an extra 8-byte discriminant word; e.g. NaN-niche keeps `?Vec` at 16 B instead of 24 B). - **Smallest example:** ```cp let hit: ?Vec = line_intersect(a, b, c, d) ``` ## Dreams Audit of every dream in `proto/ports/*/dream/` that touches `std.geometry`: 1. **`proto/ports/ecnerwala/dream/cf1146h.cp`** - Uses `use std.geometry.{Pt, turn}`, `[V]Pt = read()`, `turn(pts[i], pts[j], pts[k]) > 0`. - **Status:** Every API is in the spec (`[have]`) with identical spelling. 2. **`proto/ports/ecnerwala/dream/cf1284e.cp`** - Uses `use std.geometry.{cross}`, `[V]Pt = read()`, `pts[v] - pts[c]`, `.sorted(by: ByAngle)`, `cross(r, s) > 0`. - **Status:** Every API is in the spec (`[have]`) with identical spelling (`Pt` and `ByAngle` are in `std.prelude`). 3. **`proto/ports/ecnerwala/dream/cf2138f.cp`** - Uses `use std.geometry.Vec`, `Vec(p, q)`, `(a - b).len`, `t / k`, `d * (i - 1)`, `t.unit`, `Map`. - **Status:** All geometry operations (`Vec`, `Add`, `Sub`, `Mul`, `Div`, `.len`, `.unit`) are in the spec (`[have]`). Two dream idioms differ intentionally by spec rule (§2): integer arguments to `Vec` / scalar ops require explicit `F64(...)` (or `Pt(p, q).to_vec`) so exact ints never silently widen to float, and `Vec` omits `Eq`/`Hash` (so the compiling port tracks integer point IDs instead of `Map`). 4. **`proto/ports/ecnerwala/dream/cf2178i.cp`** - Uses `let p: [V]Vec2<1..=100> = read()` and `(p[u] - p[v]).norm2 == k`. - **Status:** Spelled `Pt` today (`[have]` in `std.prelude`, with `Sub` and `.norm2`), and `Pt<1..=100>` once range-parameterized structs (`## Powers` #3) land — `std.geometry` spells the integer 2D point type `Pt`, not `Vec2`. --- # Round 4: graphs and trees URL: /docs/ref/lib/graphs-trees Normative text from [spec/lib/graphs-trees.md](https://github.com/ryanbai1412/cp-lang/blob/main/spec/lib/graphs-trees.md). Built on rounds 1 to 3: vertices and edges are domains, per-vertex data is `[V]T`, generators drive traversals, DP tables are typed by their state. ## The model in one paragraph Vertices and edges are separate domains, so `[V]T` and `[E]T` never mix. Every algorithm takes a **`Next`**: anything that walks the arcs out of a vertex. A stored `Graph`, a `[V]List` of arcs and any fn from a vertex to a `Seq` of arcs all are one, so grids, state spaces and filtered graphs need no adjacency build. An arc is anything with `.to`; what else it carries decides which algorithms take it: `.w` for shortest paths, `.e` for bridges. Weights live on the arcs or come from `g.weighted(f)`; no algorithm takes a `w:` argument. Results that name new groups (components, blocks) return a fresh domain. A tree is `Rooted`: one structure with a fresh preorder domain `t.Pre` in which every subtree and every heavy chain is one range, so range structures (segment trees, Fenwicks) index it directly. Decision 146 records the design and its reasons. ## Graphs ```cp domain V = 1..=n domain E = 0..m let edges = read<[E](u: V, v: V, w: 1..=1e9)>() let g = Graph.undirected(edges) // or .directed; immutable CSR, O(n + m) for a in g[u]: relax(a.to, a.w) // arcs out of u, input order; a is (to, e, w) g.deg(u) // O(1) ``` | Form | Meaning | Cost | |---|---|---| | `Graph.directed(edges)`, `Graph.undirected(edges)` | build from any `[E]` of records with `u: V, v: V` | O(n + m) | | `keep: a => (to: a.to, w: a.w)` | choose what each arc stores; run once per arc | O(n + m) | | `g[u]` | `Indexed` view of `u`'s arcs, in input order | O(1) | | `g.deg(u)` | arcs out of `u` | O(1) | | `g.next(u)` | where `u`'s arcs lead (`g.out(u)` mapped to `.to`) | O(1) per arc | | `g.weighted(f)` | the same graph with `.w` read as `f(a)` | O(1); `f` per read | | `g.transpose()` | arcs reversed, other fields kept | O(n + m) | | `g.only(keep)` | induced view: arcs touching a vertex `keep` rejects are skipped | O(1) to make | | `g.only(from: f)` | arcs leaving a vertex `f` rejects are skipped (a stop vertex: arrive, never leave) | O(1) to make | | `g.matrix()` | `[V, V]?W`, least weight per pair | O(n² + m) | | `Graph.of(arcs)` | build from any `Seq` of `(from: V, arc: A)` | O(n + m) | ### Storage `Graph` is compressed sparse rows: n + 1 offsets and one list of arcs, each vertex's arcs contiguous and in input order (a counting sort, so DFS order and lexicographic answers are deterministic). An undirected edge is two arcs with the same `e`; a loop gives two arcs, so degree counts it twice. Integer widths come from the domains. **What an arc stores.** By default an arc is the edge record with `u`, `v` replaced by `to` and `e`, `EdgeArc = (to: V, e: E, ..R without (u, v))`, so `a.w` reads the arc you are already on (the `adj[u].push_back({v, w})` layout). `keep:` narrows or computes: ```cp Graph.undirected(edges) // (to, e, w): 12 bytes at these widths Graph.undirected(edges, keep: a => (to: a.to, w: a.w)) // no e: not Edged, 8 bytes Graph.directed(edges, keep: a => (to: a.to)) // bare targets Graph.undirected(edges, keep: a => (to: a.to, e: a.e, fwd: a.to == edges[a.e].v)) ``` `keep` runs once per stored arc at build (2m times for undirected), and what it returns is stored: `a.fwd` is a field load later. The returned record decides the capabilities: no `e`, not `Edged`, and `bridges(g)` is a compile error that says to keep `e`. Carried fields are copies of plain fields; a heap field (`name: Str`) is a compile error at the build that points at `keep:`, where you write `.clone()` yourself. The graph does not hold `edges`; `edges[a.e]` still works for rarely read fields. **No `add_edge`.** A graph that grows is the plain container, already a `Next`: ```cp var adj: [V]List<(to: V, w: Int)> = [] adj[u].push((to: v, w: c)) dijkstra(adj, from: [(s, 0)]) ``` Rejected: `[V]List` inside `Graph` (one allocation per vertex), forward-star lists (poor locality), arcs of `(to, e)` only with fields read from `edges[e]` (a cache miss per arc), `e` in a side table (rarely worth it). Validated input types (`Tree`, `SimpleGraph`, `ConnectedGraph`, `Dag`, `Digraph`) read like the plain edge list and also tell `cpl stress` what to generate and shrink. ### Traits ```cp pub trait Next: type Arc: Target fn out(self, u: V) -> yields Self.Arc pub trait Target: @get fn to(self) -> V // a plain vertex is its own target pub trait Weighted: @get fn w(self) -> W pub trait Edged: @get fn e(self) -> E pub trait WeightedNext = Next where Self.Arc: Weighted pub trait EdgedNext = Next where Self.Arc: Edged ``` A record with a `to`, `w` or `e` field satisfies the matching trait (a field is a `@get`); a named struct opts in with a bodiless `impl Weighted for Road`. Signatures use inline bounds and take the weakest capability they use: ```cp pub fn dijkstra(g: WeightedNext, from: Seq<(V, W)>, until: ?V = None) ``` | Takes | Algorithms | |---|---| | `Next` | BFS, DFS, topological order, SCC, components, matching, cycles | | `WeightedNext` | Dijkstra, 0-1 BFS, Dial, Bellman-Ford, Johnson, negative cycles | | `EdgedNext` | bridges, two-edge components, edge blocks | | edge records `(u, v, w, ..)` | Kruskal, arborescence, Euler walks, offline connectivity | | `[V, V]` matrix | Floyd-Warshall | | own mutable struct | flows | Whole-graph algorithms (SCC, components, bridges) also need `V: Domain`. ### Customizing: a lambda over `g.out(u)` ```cp dijkstra(u => g.out(u).filter(a => !banned[a.e]), from: [(s, 0)]) // arcs keep .w, .e bfs(u => g.out(u).filter(a => a.w <= mid), from: [s]) // binary search on the answer bfs(c => c.adj4.filter(c => grid[c] != '#'), from: [start]) // implicit grid dijkstra(g.weighted(a => 2 * a.w), from: [(s, 0)]) // reweight; keeps .to, .e dijkstra((v, k) => chain( // state space (vertex, coupons) g.out(v).map(a => (to: (a.to, k), w: a.w)), g.out(v).filter(_ => k < K).map(a => (to: (a.to, k + 1), w: a.w / 2)), ), from: [((s, 0), 0)]) ``` - `filter` keeps the arc type, so a filtered graph is still `Weighted` and `Edged`; `map` to a record makes new arcs. - Nothing is allocated: the lambda is a generator, and captures are lent per call. - One way per job: no `g.filter_arcs` or `g.restrict`. `.weighted(f)` exists because it forwards `.e` for you; `.weighted((u, a) => ...)` also passes the source vertex (Johnson potentials). - **Storage follows the vertex type.** A domain gives `[V]` arrays; any other hashable type gives hash maps. `cpl explain` shows which. ### Shortest paths All return `Paths`: | On `p` | Meaning | |---|---| | `p[v]` | distance, `?W` (`None` when unreachable) | | `p.back[v]` | `?(from: V, via: A)`, the step that reached `v` | | `p.path(t)`, `p.arcs(t)` | one shortest path, `?List` | | `p.order` | reached vertices in settling order | | Form | Weights | Cost | |---|---|---| | `bfs(g, from:, until:)` | unit | O(n + m) | | `bfs01(g, from:, until:)` | 0 or 1 | O(n + m) | | `dial(g, from:, max_w:, until:)` | small ints | O(n · max_w + m) | | `dijkstra(g, from: [(s, d0)], until:)` | non-negative | O(m log n) | | `bellman_ford(g, from:)` | any; `None` on a negative cycle | O(n m) | | `floyd_warshall(mut d, over: Semiring(min, +)) -> Bool` | dense, in place; `false` on a negative cycle; `over: Semiring(max, min)` gives widest paths | O(n³) | `until: t` stops once `t` is settled. `from:` is any `Seq`; multi-source is a longer one. `p.tight(g)` is the shortest-path DAG. All-pairs on a dense graph starts from the weight matrix: ```cp var d = g.matrix() // [V, V]?W, O(n² + m) if not floyd_warshall(mut d): print("NEGATIVE CYCLE") ``` ### Traversal generators ```cp for step in dfs(g, from: [s]): match step: Enter(v, _) => if seen_enough(v): step.prune() Exit(v, _) => done[v] = true Again(_, _) => () ``` `dfs` yields `Enter(v, via:)`, `Exit(v, via:)` (`via` the discovering arc, `None` at a source) and `Again(from, via)`, takes an optional shared `seen: mut [V]Bool`, and supports `step.prune()` after `Enter`, `break` and `return` (round 2's generators). A DFS tree with edge classification is `g.dfs_tree(root)`. ### Structure Every grouping returns a fresh domain and the map into it: | Form | Result | Cost | |---|---|---| | `components(g)` | `(domain C, comp: [V]C)` | O(n + m) | | `complement(g)` | the complement graph of the missing arcs `g`: `bfs`, `dfs`, `reachable` and `components` over it cost O(n + m) | O(1) to make | | `scc(g)` | `(domain C, comp: [V]C)`, `C` in topological order | O(n + m) | | `condense(g, comp)` | `[C]List<(to: C)>`, the arcs between components | O(n + m) | | `two_edge_components(g)` | `(domain C, comp: [V]C)` | O(n + m) | | `blocks(g)` | `(domain B, block: [E]B)`, biconnected blocks of edges | O(n + m) | | `bridges(g)`, `cut_vertices(g)` | `[E]Bool`, `[V]Bool` | O(n + m) | | `topo(g)` | `?List`, `None` on a cycle | O(n + m) | | `two_color(g)` | `?[V]Bool`, `None` when an odd cycle exists | O(n + m) | | `find_cycle(g)` | `?List` | O(n + m) | | `kruskal(edges)` (records with `w`) | `(total, take: [E]Bool)` | O(m log m) | | `euler_walk(edges, directed:)` | `?Walk` | O(n + m) | | `TwoSat()`, `.add_or(a, b)`, `.solve()` | `?[X]Bool` | O(n + m) | | `Functional(next: [V]V)` | `.after(v, k)`, `.on_cycle(v)`, `.cycle_len(v)`, `.root_of(v)` | O(n log n) build | Flows and matchings are their own module (`std.flow`), on the same `V`/`E` domains. ## Trees ```cp let t = Rooted(g, root: V.first!) // or Rooted.from_parents(par), Rooted.try_from_parents(par), Rooted.forest(g, from:) ``` | Form | Meaning | Cost | |---|---|---| | `t.parent(v)` | `?V` | O(1) | | `t.child_arcs(v)` | the arcs from `v` to its children, with their fields | O(1) per child | | `Lift.of(next)` | binary lifting over any partial successor `V -> ?V` (a greedy "next pick") | O(n log n) build | | `t.up_arc(v)` | `?A`: the arc `v` was entered by, with its fields (`t.up_arc(v)!.cost`) | O(1) | | `t.children(v)` | `Indexed` view of `v`'s children (stored contiguously) | O(1) | | `t.depth(v)`, `t.size(v)` | edges from the root; vertices in the subtree | O(1) | | `t.order` | every vertex, parents before children (BFS order); `.rev` is children first | O(1) | | `t.lca(a, b)`, `t.dist(a, b)`, `t.is_anc(a, b)` | | O(log n) | | `t.ancestor(v, k)`, `t.jump(a, b, k)` | `?V`: k steps up; k steps along the path a → b | O(log n) | | `t.path(a, b)` | `List` | O(length) | | `t.diameter()`, `t.centroid()` | `(len, u, v)`; a centroid | O(n) | **Tree DP without recursion** walks `t.order.rev`: ```cp var size: [V]Int = 1 for v in t.order.rev: for c in t.children(v): size[v] += size[c] ``` The library forms for the shapes that recur: | Form | Meaning | Cost | |---|---|---| | `t.up(op, lift:, finish:)` | bottom-up DP: fold children with `op` | O(n) calls | | `t.reroot(op, lift:, finish:)` | the same DP for every root at once; no inverse needed | O(n) calls | | `t.down(init, f)` | top-down: `out[v] = f(out[parent], v)` | O(n) calls | Recursion stays available and natural (`for c in t.children(v): mine.absorb(go(c))`). ### Subtrees and paths are ranges `t.Pre` is a fresh domain per tree: an Euler order where every subtree and every heavy chain is contiguous. `t.pos(v): t.Pre`; another tree's `Pre` doesn't mix. ```cp var seg = SegTree(max, t.reorder(val)) // [t.Pre]T seg.fold(t.sub(v)) // subtree query: one range t.fold_path(a, b, seg) // path query: O(log n) ranges (HLD) t.apply_path(a, b, lazy, add(x)) for r in t.chains(a, b): ... // the ranges themselves, when you need them ``` | Form | Meaning | Cost | |---|---|---| | `t.sub(v)`, `t.below(v)` | `Range`: subtree with / without `v` | O(1) | | `t.chains(a, b)` | `yields Range`, ordered from `a` to `b` | O(log n) ranges | | `t.fold_path(a, b, ds, edges:)`, `t.apply_path(...)` | path fold / update over any range structure | O(log n) ranges | | `t.tour` | `yields Visit`: `Enter` / `Exit` events, `via` the parent | O(1) to make, O(n) to walk | | `t.virtual(keys)` | the virtual (auxiliary) tree of `keys` | O(k log k) | | `Centroids(g)` | centroid decomposition: `.parent(c)`, `.ancestors(v)` with distances | O(n log n) | ### Changing trees `LinkCut(op)`, `LazyLinkCut`, `EulerTourTree`, `JumpTree` (online binary lifting as leaves are added), `PreferredPaths(t)` (the access half of a link-cut tree over a fixed `Rooted`; `access(v)` yields each path switch, the shape of "colours painted along root paths" problems). Same vertex domain, same method names as `Rooted` where they mean the same thing (`lca`, `dist`, `jump`, `fold_path`). ### Also in the prelude | Form | Meaning | Cost | |---|---|---| | `Lit(x, value)` | a 2-SAT literal, "x is `value`", for `TwoSat` | O(1) | | `p.adj4`, `p.adj8`, `p.ray(d)`, `Dir4`, `Dir8` | grid neighbours of a `(Row, Col)` cell inside the grid; the cells from `p` to the edge in direction `d` | O(1) per cell | | `kruskal_tree(es, w:)`, `KruskalTree` | the reconstruction tree over a fresh node domain; `reach(v, limit:)` is one subtree, `top(v, ok:)` tests the merging edges themselves, `up(op, leaf:)` folds leaf values per node; flip the order with `w: e => desc(e.w)` | O(m log m), O(log n) per `reach` | ## Open 1. **Weight algebra.** Dijkstra's distance is `Ord + Add + Zero` today. Ryan leans to a monoid-like argument so minimax, bottleneck and reliability paths are one call; not designed yet. 2. **Hash-backed state spaces.** Storage follows the vertex type: a domain gives arrays, anything hashable gives maps. Alternative: require a domain and make the user `compress` first. 3. **Tuples as edges.** Builds need named records (`read<[E](u: V, v: V)>`); several dreams still pass unnamed `(V, V)` tuples and need the one-line `map` that names them. --- # Standard library design: number theory, combinatorics, NTT and linear algebra URL: /docs/ref/lib/math Normative text from [spec/lib/math.md](https://github.com/ryanbai1412/cp-lang/blob/main/spec/lib/math.md). > **0.3.0 status.** This chapter is the family's design survey and API. > Where it disagrees with the core chapters or the aligned rounds, they > win: `core/03-numbers-layout.md` (four number types, no `I32`/`U32`, > `Mod

` not `Mint`), `core/05-ownership.md` (constructors own their > results), `core/07-sequences.md` (capabilities, views keep keys), > `lib/ops-ranges.md` (`Op`/`Monoid`/laws, `each(...)`, no > `RangeFenwick`, `MinHeap`/`MaxHeap` as `Heap(by:)`) and > `lib/sequence-patterns.md`. The stubs in `std/` are the signatures of > record. Reconciliation of this text is tracked in `delta/`. This document designs the five mathematical modules of the CP Lang standard library: `std.math` (integer number theory and sieves), `std.mod` (modular arithmetic and combinatorics), `std.ntt` (number-theoretic and bitwise convolutions), `std.poly` (formal power series over NTT), and `std.matrix` (dense matrices, Gaussian elimination and GF(2) linear bases). It corresponds to sections 4.3 through 4.6 of `plan/STDLIB.md`. Every design choice follows `AGENTS.md` and `plan/STDLIB.md`: ordinary CP Lang with no compiler privilege, guessable textbook names, options as named arguments, documented time and memory cost on every public item, explicit representation, and algebraic laws checked by `@test`. ## 1. Survey of contest patterns A survey of Codeforces Div. 1/2, AtCoder ABC/ARC/AGC/WTF, ICPC World Finals, KACTL (`number-theory/`, `numerical/`), AtCoder Library (`math.hpp`, `modint.hpp`, `convolution.hpp`), and the 60+ math-bearing accepted submissions in `proto/ports/ecnerwala/*_orig.cpp` shows seven recurring contest shapes. First, **basic integer arithmetic and divisibility**: `gcd`, `lcm`, Bezout coefficients (`ext_gcd`), Euclidean and ceiling division, modular inverses for dynamic non-type moduli (`inv_mod`), exact binomials (`choose`), `choose2(n)` for pair counts, and `floor_sum` for lattice-point and arithmetic-progression sums. In `proto/ports/ecnerwala/`, `gcd`/`ext_gcd` appear in 11 submissions and `floor_sum` is a standard AtCoder Library building block. Second, **primality, sieves, factorization and multiplicative functions**: three distinct cost regimes appear in contests. For many queries up to `n <= 2e7`, a linear sieve (`Sieve(n)`) gives `O(1)` primality, `O(log x)` factorization, and `O(d(x))` divisor enumeration, plus `O(n)` tables of any multiplicative function (`phi`, `mobius`, divisor sums, or custom recurrences like `cf2135e2`'s `odd_div_sum`). For a single number up to `1e12`, trial division (`factor`, `divisors`, `phi`) is `O(sqrt x)` with no setup. For numbers up to `2^62`, deterministic 12-base Miller-Rabin (`is_prime`) and Pollard's rho with Brent batching (`factor` above `10^6`) handle arbitrary 64-bit inputs. Rounding out elementary number theory are `crt` / `crt_all` (general non-coprime moduli), `primitive_root`, `mod_log` (BSGS discrete logarithm), and `mod_sqrt` (Tonelli-Shanks). Third, **modular arithmetic with compile-time and runtime moduli**: `modnum` appears in 60 ecnerwala submissions. The modulus is usually a prime constant (`998_244_353` or `1_000_000_007`), sometimes a composite or runtime-read integer, and occasionally a 60-bit prime for hashing. One type `Mod

` serves all of them: the modulus is part of the type, takes zero storage per value, and prevents mixing two moduli. Fourth, **combinatorial counting tables tied to `Mod

`**: factorial and inverse-factorial tables appear in 25 ecnerwala submissions (`cf2066d2`, `cf2084e`, `cf2135e2`, `cf2150g`, etc.). Every such solution wants `fact`, `inv_fact`, `inv(i)` in `O(1)`, `choose(n, k)` (with `0` outside `0..=n` and Lucas's theorem when `n >= P`), `arrange`, `multichoose`, `multinomial`, and `catalan`, without repeating the modulus literal after `type Z = Mod

`. Fifth, **polynomial and bitwise convolutions**: NTT appears in 7 ecnerwala submissions and 9 corpus ports (`lib.math.poly`). Contests need four closely related operations: in-place `ntt`, polynomial multiplication over an NTT-friendly `Mod

`, arbitrary-modulus multiplication via 3-prime CRT, and exact signed integer convolution (requested by `research/frictions/cf2201e.md`), all one `convolve` whose value type picks the algorithm. Both linear and cyclic convolutions (`cyclic: true`) occur regularly. Alongside NTT, bitwise convolutions (`convolve(a, b, on: |)`, `on: &`, `on: ^`) and subset/superset zeta-Mobius transforms (one `sos(a, over: Sub | Sup, inverse:)`) cover `O(n 2^n)` bitmask DP. Sixth, **dense matrices and Gaussian elimination**: linear recurrences and walk counting (`Mat.pow`, `Mat.apply`), matrix-DP segment trees (`Mat.product`), and linear algebra over prime fields `Mod

` and reals `F64` (`det`, `rank`, `solve`, `solve_space`, `inverse`). Flat row-major storage matters for cache locality; elimination is exact over `Mod

` and uses partial pivoting with a configurable tolerance `eps` over `F64`. Seventh, **GF(2) linear bases**: XOR subset maximization, membership, k-th smallest XOR, and merging bases inside segment trees or DSU-on-tree (`cf2115d`, `cf2262e`, `ucup5s05f`, CF 1100F). A compact `XorBasis` type with a `Monoid` combinator eliminates a recurring 20-line template. ## 2. Coherent API surface ### 2.1 `std.math`: integer helpers, number theory and sieves Every function documents its cost and its regime. Where two algorithms exist for the same mathematical operation, the cost is visible in the name or type: `Sieve(n).factor(x)` is `O(log x)` after `O(n)` setup, and standalone `factor(x)` is `O(sqrt x)` for `x <= 1e6` and `O(x^(1/4) log x)` expected above. ```cp // Divisibility, division, and exact combinatorics fn gcd(a: Int, b: Int) -> Int // O(log min(|a|, |b|)); >= 0, gcd(0,0) = 0 fn lcm(a: Int, b: Int) -> Int // O(log min(|a|, |b|)); >= 0, traps on overflow fn ext_gcd(a: Int, b: Int) -> (g: Int, x: Int, y: Int) // O(log min(|a|, |b|)); a*x + b*y == g >= 0 fn ceil_div(a: Int, b: Int) -> Int // O(1); b != 0 fn divmod(self: Int, d: Int) -> (Int, Int) // O(1); Euclidean (self / d, self % d), 0 <= r < |d|, d != 0 fn fixed(num: Int, den: Int, k: Int) -> Str // O(k); exact integer decimal formatting fn choose(n: Int, k: Int) -> Int // O(min(k, n - k)); 0 outside 0..=n fn choose2(n: Int) -> Int // O(1); n * (n - 1) / 2, 0 for n < 2 // Bit and digit helpers fn bit_len(x: Int) -> Int // O(1); 0 for x == 0 fn digits(self: Int, base: Int = 10) -> List // O(log_base x); lowest digit first @get fn sign(self: Int) -> Sign // O(1); Neg, Zero or Pos fn bit(self: Int, i: Int) -> Bool // O(1); bit 0 is lowest @get fn is_pow2(self: Int) -> Bool // O(1); x > 0 and x & (x - 1) == 0 fn splitmix64(x: U64) -> U64 // O(1); 64-bit mixing finalizer // Modular integer arithmetic (dynamic modulus without Mod

) fn mul_mod(a: Int, b: Int, m: Int) -> Int // O(1); exact via I128 when needed, m >= 1 fn pow_mod(a: Int, e: Int, m: Int) -> Int // O(log e); e >= 0, m >= 1 fn inv_mod(a: Int, m: Int) -> ?Int // O(log m); m >= 1, None if gcd(a, m) != 1 fn crt(r1: Int, m1: Int, r2: Int, m2: Int) -> ?(Int, Int) // O(log min(m1, m2)); non-coprime allowed fn crt_all(eqs: List<(Int, Int)>) -> ?(Int, Int) // O(k log M); folds crt over a system fn mod_log(a: Int, b: Int, m: Int) -> ?Int // O(sqrt m); smallest x >= 0: a^x = b (mod m) fn mod_sqrt(a: Int, p: Int) -> ?Int // O(log^2 p); prime p, x^2 = a (mod p) fn primitive_root(p: Int) -> Int // expected O(p^(1/4) log p); prime p fn floor_sum(n: Int, m: Int, a: Int, b: Int) -> Int // O(log m); sum_{i in 0..n} floor((a*i+b)/m) // Primality and factorization (single-input) fn is_prime(x: Int) -> Bool // O(log^2 x); deterministic Miller-Rabin, all Int fn factor(x: Int) -> List<(Int, Int)> // O(sqrt x) <= 1e6, O(x^(1/4) log x) expected above fn divisors(x: Int) -> List // O(sqrt x); sorted fn divisors_from_factors(fs: List<(Int, Int)>) -> List // O(d(x) log d(x)); sorted divisors from factors fn phi(x: Int) -> Int // O(sqrt x); Euler's totient // Linear sieve and multiplicative tables struct Sieve: // O(n) time and memory spf: List<0..=2_000_000_000> // smallest prime factor, 0 for 0 and 1 primes: List<0..=2_000_000_000> // all primes in 2..=n, ascending fn new(n: Int) -> Sieve // O(n) fn is_prime(self, x: Int) -> Bool // O(1) fn factor(self, x: Int) -> List<(Int, Int)> // O(log x) fn divisors(self, x: Int) -> yields Int // O(1) per divisor; unordered fn phi(self, x: Int) -> Int // O(log x) fn mobius(self, x: Int) -> Int // O(log x) fn phi_table(self) -> List // O(n); totient[0..=n] fn mobius_table(self) -> List // O(n); mu[0..=n] fn sieve_multiplicative( n: Int, prime_pow: (Int, Int, Int) -> T, ) -> List // O(n) time and memory; computes f[0..=n] for any multiplicative f // with f(1) = T.one, f(a * b) = f(a) * f(b) for gcd(a, b) = 1, // and f(p^k) = prime_pow(p, k, p^k) for every prime power p^k <= n. ``` `sieve_multiplicative` takes only `prime_pow`; `T.one` and `*` come from the value type, as for every other algebraic default, so `Int`, `Mod

` and user structs with `One` and `Mul` all work. Two statistics at once use a record type with its own `*`. It runs in strict `O(n)` time by tracking the largest prime-power divisor `low[i]` of each `i`. ### 2.2 `std.mod`: modular arithmetic and combinatorics `Mod

` is one type for both compile-time constants (`type Z = Mod<998_244_353>`) and runtime moduli (`let P: Int = read(); type Z = Mod

`). `Comb` is keyed on the `Mod` type (`let comb = Comb(limit)`) so the modulus is written once. ```cp struct Mod

(v: 0..P): let MOD = P let zero = Mod(0) let one = Mod(1 % P) fn new(x: Int) -> Mod

// O(1); Euclidean reduction into 0..P // x ** e via `impl Pow`: O(log |e|); negative e uses inv fn try_inv(self) -> ?Mod

// O(log P); None if gcd(v, P) != 1 fn inv(self) -> Mod

// O(log P); traps if non-invertible // also: from_int, sqrt, log, inv_all; Comb.derange, Barrett, PrimePowerComb, // ModComb (see the std.mod stub) // impls: Add, Sub, Neg, Mul, Div, Pow, Show struct Comb: fn new(limit: Int = 0) -> Comb // O(limit) time and memory; exact size fn fact(self, n: Int) -> M // O(1) amortized; 0 for n >= M.MOD fn inv_fact(self, n: Int) -> M // O(1) amortized; 0 <= n < M.MOD fn inv(self, i: Int) -> M // O(1) amortized; 1 <= i < M.MOD fn choose(self, n: Int, k: Int) -> M // O(1) for n < M.MOD; Lucas O(log_P n) for n >= M.MOD fn arrange(self, n: Int, k: Int) -> M // O(1) amortized; 0 outside 0..=n fn multichoose(self, n: Int, k: Int) -> M // O(1) amortized; stars and bars fn multinomial(self, ks: List) -> M // O(ks.len) amortized; (sum ks)! / prod(k!) fn catalan(self, n: Int) -> M // O(1) amortized ``` Performance notes from the corpus (`cf2135e2`, `cf2150g`, `cf2066d2`, `cf2062h`, `cf2084e`): 1. `Comb.new(limit)` sizes `f` and `g` to `limit + 1` directly and fills `g` in place without allocating a temporary `tail` buffer. Lazy growth via `ensure(n)` still doubles capacity (clamped at `P`), also filling `g` in place. This cuts peak memory on `n = 2e7` by ~350 MB. 2. `choose(n, k)` and `arrange(n, k)` take a single fast-path branch `if n < f.len` before checking `n >= P` or calling `ensure`, because `f.len <= P` is an invariant of `Comb

`. 3. Storage width: today `Mod

(v: Int)` uses 8 bytes per value because type-parameter range narrowing (`v: 0..P`) is not yet in `cpl-check`/ `cpl-codegen`. That is the single largest remaining performance gap on dense `Mod

` tables (`cf2150g`, `cf2135e2`, `cf2062h`). Narrowing `0..P` to `uint32_t` when `P <= 2^31 - 1` is tracked for the core/codegen lane and requires no API change in `std.mod`. ### 2.3 `std.ntt`: NTT and bitwise convolutions `std.ntt` promotes the radix-4 Montgomery NTT engine from `examples/local-lib/math/poly.cp` into a clean, generic stdlib module and adds cyclic convolution and bitwise transforms. ```cp // Number-theoretic transform and polynomial convolution fn ntt

(mut a: List>, inverse: Bool = false, bit_reversed: Bool = false) // O(n log n) in place; a.len a power of 2 dividing P - 1. // Uses radix-4 Montgomery butterflies for standard primes (998244353, // 469762049, 167772161, 754974721) and primitive_root(P) for any other // NTT-friendly prime P. fn convolve( a: List, b: List, on: O = (x, y) => x + y, // ^ | & subset gcd lcm over: R = Semiring(+, *), // Semiring(min, +) needs shape: shape: ?Curved = None, // Both | Right | Neither cyclic: Bool = false, ) -> List // The value type picks the algorithm: NTT for an NTT-prime Mod

, three // primes and CRT for any other Mod (runtime moduli too) or Int (exact when // every output fits), FFT for F64. Bitwise `on:` needs equal powers of two. // Subset/superset zeta-Mobius transforms in place (n = 2^k) enum SosOver = Sub | Sup fn sos(mut a: S, over: SosOver = Sub, inverse: Bool = false) ``` Notice the uniform design: one `convolve` (ops-ranges §13), with `cyclic:`, `on:` and `over:` as named arguments. All bitwise transforms infer the number of bits from `a.len` (asserting `a.len.is_pow2`), avoiding a redundant `bits` argument that can go out of sync with `a.len`. ### 2.4 `std.matrix`: dense matrices, Gaussian elimination and `XorBasis` > The names of record are `std/matrix.cp`'s: `Mat.zeros(n, m)`, `Mat.from_rows(rows)`, > `rows`/`cols`/`data`, `impl Pow`, and `A.mul_vec(x)` for `A.apply(x)`; there is no > `impl Neg`. `XorBasis` holds 63-bit non-negative values; `new` and `add` are O(W). `Mat` stores entries in a single flat row-major `List` of length `n * m` so multiplication and elimination stay cache-friendly. ```cp struct Mat(n: Int, m: Int, a: List): fn zero(n: Int, m: Int = n) -> Mat // O(n m) fn identity(n: Int) -> Mat // O(n^2) fn of(rows: List>) -> Mat // O(n m) fn get(self, i: Int, j: Int) -> T // O(1) fn at(self, i: Int, j: Int) -> lends mut T // O(1); writable cell: m.at(i, j) += x fn pow(self, e: Int) -> Mat // O(n^3 log e); square matrix, e >= 0 fn apply(self, v: List) -> List // O(n m); A * v fn transpose(self) -> Mat // O(n m) fn rows(self) -> List> // O(n m) fn product(n: Int) -> Monoid> // O(n^2); monoid for SegTree> // impls: Add, Sub, Neg, Mul (ikj order, skipping zero entries) // Exact Gaussian elimination over any exact field (e.g. Mod

with prime P): fn det(self) -> T // O(n^3); square matrix fn rank(self) -> Int // O(n m min(n, m)) fn solve(self, b: List) -> ?List // O(n m min(n, m)); one solution or None fn solve_space(self, b: List) -> ?(x0: List, basis: List>) // O(n m min(n, m)); particular + nullspace fn inverse(self) -> ?Mat // O(n^3); square matrix, None if singular // Floating-point elimination with partial pivoting (F64): fn det_real(a: Mat, eps: F64 = 1e-9) -> F64 // O(n^3) fn rank_real(a: Mat, eps: F64 = 1e-9) -> Int // O(n m min(n, m)) fn solve_real(a: Mat, b: List, eps: F64 = 1e-9) -> ?List // O(n m min(n, m)) fn inverse_real(a: Mat, eps: F64 = 1e-9) -> ?Mat // O(n^3) // GF(2) linear basis over 63-bit non-negative integers (x >= 0) struct XorBasis: fn new() -> XorBasis // O(W) @get fn rank(self) -> Int // O(1); dimension of span fn add(mut self, x: Int) -> Bool // O(log x); true if independent fn reduce(self, x: Int) -> Int // O(62); min x ^ s over s in span fn contains(self, x: Int) -> Bool // O(62); reduce(x) == 0 fn max_xor(self, init: Int = 0) -> Int // O(62); max init ^ s over s in span fn min_xor(self, init: Int) -> Int // O(62); alias for reduce(init) fn kth(self, k: Int) -> ?Int // O(62^2); k-th smallest in span (0-indexed) fn merge(mut self, o: XorBasis) // O(rank * 62); union of spans fn monoid() -> Monoid // O(1); for SegTree ``` Why `det_real` / `solve_real` are separate from `Mat.det` / `Mat.solve`: floating-point elimination needs partial pivoting by `abs` and a tolerance `eps`, whereas exact elimination over `Mod

` checks `== T.zero` and divides directly. Keeping exact field methods on `Mat` and pivoted real helpers explicit avoids hidden `F64` specialization and respects CP Lang's rule that float equality is rejected by default. ### 2.5 `std.poly`: formal power series over NTT `std.poly` operates directly on `List>` (lowest degree first, identical to `std.ntt.convolve

`), with no wrapper struct so series compose directly with `std.ntt`, `Comb>`, and list comprehensions. Every truncated FPS operation takes an explicit output length `n: Int` (computing modulo `x^n`, returning a `List>` of length `n`, with `n == 0` returning `[]`) and requires an NTT-friendly prime `P` (`P - 1` divisible by a power of two at least `2 * bit_ceil(n)`). ```cp fn deriv

(a: List>) -> List> // O(a.len) time and memory; formal derivative a'(x), length max(0, a.len - 1) fn integral

(a: List>) -> List> // O(a.len) time and memory; antiderivative with constant term 0, length a.len + 1 // (or [] if a is empty); uses linear-time modular inverses 1..=a.len, no O(log P) div fn inv

(a: List>, n: Int) -> List> // O(n log n) time (~10n log n via half-size Newton doubling: 5 NTTs of size 2m per // doubling step m -> 2m), O(n) memory; returns a(x)^(-1) mod x^n. // Precondition: n >= 0; if n > 0, a.len > 0 and a[0] != 0. fn log

(a: List>, n: Int) -> List> // O(n log n) time (1 inv + 1 convolve + deriv + integral, ~13n log n), O(n) memory; // returns ln(a(x)) mod x^n = integral(a'(x) * a(x)^(-1)) mod x^n. // Precondition: n >= 0; if n > 0, a.len > 0 and a[0] == 1. fn exp

(a: List>, n: Int) -> List> // O(n log n) time (Newton doubling g <- g * (1 - ln(g) + a) mod x^(2m), ~28n log n), // O(n) memory; returns exp(a(x)) mod x^n. // Precondition: n >= 0; if n > 0, a.len == 0 or a[0] == 0. fn pow

(a: List>, k: Int, n: Int) -> List> // O(n log n) time (1 log + 1 exp when nonzero, O(n) when k == 0 or shifted past n), // O(n) memory; returns a(x)^k mod x^n for k >= 0, handling leading zeros a(x) = c x^d (...). // Precondition: n >= 0, k >= 0. fn sqrt

(a: List>, n: Int) -> ?List> // O(n log n + log^2 P) time (Tonelli-Shanks mod_sqrt for leading term + Newton doubling // g <- (g + a * g^(-1)) / 2 mod x^(2m), ~20n log n), O(n) memory. // Returns Some(g) with g(x)^2 == a(x) (mod x^n), or None if no square root exists mod P // (odd leading zero count or non-residue leading coefficient). // Precondition: n >= 0. ``` Cost summary (NTTs of length `N = bit_ceil(n)`): - `deriv`, `integral`: `O(n)` time, `0` NTTs (`integral` computes `inv[1..=n]` in `O(n)` via `inv[i] = -(P / i) * inv[P % i]`). - `inv`: ~`5` NTTs of size `2m` per doubling (`m = 1, 2, ..., N/2`), geometric total ~`10` NTTs of size `N`. - `log`: `inv(a, n)` + 1 `convolve` of length `n` + `deriv`/`integral`. - `exp`: Newton doubling calling `log` + 1 `convolve` at each doubling `m -> 2m`. - `pow`: `O(n)` normalization + 1 `log` + 1 `exp` + `O(n)` rescaling (no `log k` factor). - `sqrt`: 1 `mod_sqrt` (`O(log^2 P)`) + Newton doubling calling `inv` + 1 `convolve` at each doubling. ### 2.6 Everyday integer helpers (all in the prelude) | Form | Meaning | Cost | |---|---|---| | `ceil_div(a, b)`, `x.divmod(d)` | ceiling division; Euclidean `(q, r)` with `0 <= r < abs(d)` | O(1) | | `x.digits(base:)`, `x.to_str(base:)` | digits lowest first; the written form, highest first | O(log x) | | `x.sign` | the side of zero, a `Sign` | O(1) | | `floor_quotients(n, from: 1)` | each distinct `n / i` for `i >= from`, with its run of `i`, `(q, lo, hi)` | O(sqrt n) | | `Ratio(p, q)` | an exact reduced rational | O(log) per op | | `coef.eval(x)` | a polynomial at `x` over any ring, by Horner | O(len) | | `Curved` | the `shape:` of a non-`(+, *)` `convolve` (`Both`, `Right`, `Neither`) | — | ## 3. Laws and invariants Every module enforces its mathematical laws in `@test`: - `std.math`: `gcd(a, b) >= 0`, `a * e.x + b * e.y == e.g == gcd(a, b)` for `e = ext_gcd(a, b)`; `crt(r1, m1, r2, m2)` returns `(r, lcm(m1, m2))` with `r % m1 == r1 % m1` and `r % m2 == r2 % m2`, or `None` iff no solution exists; `is_prime(x)` agrees with `Sieve` and rejects Carmichael numbers and strong pseudoprimes; `factor(x) == s.factor(x)` and their product equals `x`; `pow_mod(a, mod_log(a, b, m)!, m) == b % m`; `mod_sqrt(a, p)! ** 2 % p == a % p`; `sieve_multiplicative` satisfies `f[a * b] == f[a] * f[b]` for coprime `a, b`. - `std.mod`: `Mod

` satisfies `laws_hold(Monoid>.of(+), xs)` and `laws_hold(Monoid>.of(*), xs)`; `x * x.inv == Mod.one` when `gcd(x.v, P) == 1`; `Comb

.choose` satisfies Pascal's identity and Lucas's theorem; `fact(n) * inv_fact(n) == one`; `inv(i) * Mod(i) == one`. - `std.ntt`: `ntt(mut a, inverse: true)` is the exact inverse of `ntt(mut a)`; `convolve` agrees with the naive `O(n m)` loop for every value type, `on:` and `over:`, both `cyclic: false` and `cyclic: true`; `sos(inverse: true)` inverts `sos`. - `std.poly`: `convolve(a, inv(a, n))[0..n] == [1, 0, ...]`; `exp(log(a, n), n) == a[0..n]` for `a[0] == 1`; `log(exp(a, n), n) == a[0..n]` for `a[0] == 0`; `pow(a, k, n)` agrees with repeated `convolve` (including leading zeros and `k == 0`); `convolve(g, g)[0..n] == a[0..n]` for `g = sqrt(a, n)!` and `sqrt(a, n) == None` for odd leading zero count or quadratic non-residue leading term; `deriv(integral(a)) == a`. - `std.matrix`: `Mat.product(n)` satisfies `laws_hold`; `(A * B).det() == A.det() * B.det()`; `A * A.inverse()! == Mat.identity(n)`; for every `x0` and `v` in `solve_space(b)!.basis`, `A.mul_vec(x0 + c * v) == b`; `XorBasis` satisfies `laws_hold(XorBasis.monoid(), xs)`, `contains(x)` iff `x` is a subset XOR of inserted elements, and `kth(0..2^rank)` is strictly increasing and exhausts the span. ## 4. Domains, index spaces and what stays user code `std.math` and `std.mod` operate on mathematical values (`Int`, `Mod

`), not array positions, so their arguments are integers and moduli rather than domains. Where a matrix or basis lives inside a range structure, it plugs directly into CP Lang's domain-indexed structures via `Monoid`: `SegTree>(Mat.product(k), init)` and `SegTree(XorBasis.monoid(), init)`. What stays in `examples/local-lib/math/` or user code (until wider corpus demand justifies promotion): - Advanced polynomial algorithms (multipoint evaluation, interpolation, Taylor shift, Bostan-Mori, polynomial GCD, composition) are in `std.poly` (see its stub); the rest stays in `examples/local-lib/math/poly.cp`. - Exact fractions (`Frac`) and homomorphisms stay in `examples/local-lib/math/`; `simplex` is in `std.matrix`. - Custom-payload XOR bases (like `cf2115d`, where each basis bit also owns a player `Bool` deciding whether to maximize or minimize that bit) stay user code because the payload semantics are problem-specific. - Arbitrary-precision `BigInt`: out of scope for v1; `I128` covers intermediate products. ## 5. Real problems written against this API Each solution below is written at the bar of `design/EXEMPLARS-PORTS.md`: the editorial invariant up front, standard algorithms named, no boilerplate. ### 5.1 Codeforces 2201 E — ABBA Counting Split `t` of length `2m` into two halves. By inclusion-exclusion on the repetition count `f | m` (period `L = m / f`), each `f` has Mobius-like weight `prod_{p | f} (1 - p)`. Cyclic exact-integer convolution counts agreements and doubly-fixed pairs for every shift at once. ```cp // A valid ABBA string of length 2m has minimal period L | m (f = m / L). // For each divisor f, fold both halves mod L and use cyclic integer // convolution to count agreements and doubly-fixed pairs per shift. @!multitest use std.math.{divisors, factor} type Z = Mod<998_244_353> let n: 2..=400_000 = read() let t: Str = read() let m = n / 2 var pow2: [0..=m]Z = 1 for i in 1..=m: pow2[i] = pow2[i - 1] * 2 var ans: Z = 0 'divisor: for f in divisors(m): let len = m / f var s: [0..2][0..len]?Char = None for z in 0..2: for k in 0..f: for i in 0..len: let c = t[z * m + k * len + i] if c == '?': continue if let prev = s[z][i], prev != c: continue 'divisor s[z][i] = c var sign0: [0..len]Int = 0 var sign1: [0..len]Int = 0 var fix0: [0..len]Int = 0 var fix1: [0..len]Int = 0 var tot_fix = 0 for i in 0..len: if let c = s[0][i]: sign0[i] = if c == 'a': 1 else: -1 fix0[i] = 1 tot_fix += 1 if let c = s[1][len - 1 - i]: sign1[i] = if c == 'a': 1 else: -1 fix1[i] = 1 tot_fix += 1 let diff_conv = convolve(sign0, sign1, cyclic: true) let both_conv = convolve(fix0, fix1, cyclic: true) var ways: Z = 0 for i in 0..len: if diff_conv[i] == both_conv[i]: ways += pow2[len - tot_fix + both_conv[i]] var w: Z = 1 for (p, _) in factor(f): w *= 1 - p ans += ways * w print(ans) ``` Compare with `proto/ports/ecnerwala/cf2201e.cp`: the `cyclic_convolve` wrapper, the `Mod<998244353>` encoding hack, and the `.v` field leak are all gone. ### 5.2 Codeforces 2135 E2 — Beyond the Palindrome (Hard Version) The editorial reduces the answer to a linear combination of binomials weighted by the multiplicative function `odd_div_sum(x) = 2^{v_2(x)} * sigma_1(x / 2^{v_2(x)})`. ```cp // odd_div_sum(x) = 2^{v_2(x)} * sigma_1(x / 2^{v_2(x)}) is multiplicative: // f(2^k) = 2^k, and for odd prime p, f(p^k) = (p^{k+1} - 1) / (p - 1). use std.math.{sieve_multiplicative} type Z = Mod<998_244_353> let t: 1..=10_000 = read() let ns: [0..t](https://github.com/ryanbai1412/cp-lang/blob/main/spec/lib/1..=20_000_000) = read() let lim = ns.max() + 1 let comb = Comb(lim) let odd_div_sum = sieve_multiplicative( lim, prime_pow: (p, _, pe) => if p == 2: pe else: (pe * p - 1) / (p - 1), ) for n in ns: var cnt: [0..=n]Z = 0 for i in 1..=n + 1: var v = Z(odd_div_sum[i]) if i % 2 == 1: v -= 1 elif n % 2 == 1 and i % 4 == 2: v -= 2 if (i + n) % 2 == 1: if i - 1 <= n: cnt[(n + i - 1) / 2] += 2 * v if i + 1 <= n: cnt[(n + i + 1) / 2] += 2 * v else: if i <= n: cnt[(n + i) / 2] -= 4 * v let ans: Z = sum(comb.inv_fact(i) * comb.inv_fact(n - i) * cnt[i] for i in 0..=n) print(ans * comb.fact(n) + Z(2) ** n) ``` Compare with `proto/ports/ecnerwala/cf2135e2.cp`: the 22-line hand-rolled linear sieve disappears into a single `sieve_multiplicative` call, and `Comb(lim)` writes the modulus once. ### 5.3 AtCoder DP R — Walk Count directed walks of length `k` in an `n`-vertex graph (`n <= 50`, `k <= 10^18`) modulo `10^9 + 7`: raise the adjacency matrix to the `k`-th power and sum all entries. ```cp // The (i, j) entry of A^k counts length-k walks from i to j. use std.matrix.{Mat} type Z = Mod<1_000_000_007> let n: 1..=50 = read() let k: 1..=1_000_000_000_000_000_000 = read() let adj = [[Z(read<0..=1>()) for _ in 0..n] for _ in 0..n] let walks = Mat.of(adj) ** k print(sum(walks.get(i, j) for i in 0..n for j in 0..n)) ``` Compare with `proto/ports/dpr.cp`: both hand-rolled matrix multiplication and binary exponentiation vanish. ### 5.4 Codeforces 1100 F — Ivan and Burgers Given an array `a[1..=n]` (`n <= 5e5`) and `q` range queries `[l, r]`, print the maximum XOR of any subset of `a[l..=r]`. A `SegTree` over `XorBasis` answers each query in `O(log n * 62)` (or offline prefix bases in `O(62)`). ```cp // XorBasis forms a monoid under merge, so a SegTree answers range max-XOR // queries directly. use std.matrix.{XorBasis} let n: 1..=500_000 = read() domain I = 1..=n let a: [I]0..=1_000_000 = read() let init = [I] i => var b = XorBasis.new() b.add(a[i]) b let seg = SegTree(XorBasis.monoid(), init) let q: 1..=500_000 = read() repeat q: let (l, r): (I, I) = read() print(seg.fold(l..=r).max_xor()) ``` ### 5.5 Codeforces 2084 E — Blossom Count the sum of `MEX` over all subarrays of all completions of a partial permutation `a`. Using `Comb(n)` keeps the modulus in one place. ```cp @!multitest type Z = Mod<1_000_000_007> let n: 1..=5000 = read() domain Pos = 0..n domain Val = 0..n let a: [Pos]Int = read() var pos: [Val]?Pos = None for i in Pos if a[i] >= 0: pos[Val(a[i])] = i let missing = prefix([Pos] i => if a[i] == -1: 1 else: 0) let m = missing.prefix(Pos.last!.r) let comb = Comb(n) // ... sweep Val, accumulating Z(freq[f]) * comb.arrange(f, need) * comb.fact(m - need) ``` --- ## 6. Matched C++17 benchmarks (`bench/math/`) `bash bench/math/run.sh` benchmarks the six core math workloads against matched C++17 (same algorithm and layout, `g++ -std=c++17 -O2`, best of 5 runs, exact stdout check, emitted C++ bytes): | Workload | Size | CP Lang | C++17 | Ratio | Emitted | |---|---|---:|---:|---:|---:| | `modint` | 10M add/sub/mul + 200K div/pow (`Mod<998244353>`) | 0.067s | 0.070s | 0.96x | 8,998 B | | `ntt` | `convolve` (`262,144 x 262,144`, Montgomery NTT) | 0.029s | 0.036s | 0.81x | 16,078 B | | `sieve` | `Sieve(5_000_000)` + `phi_table` + `mobius_table` | 0.095s | 0.086s | 1.10x | 4,675 B | | `matpow` | `80 x 80` `Mat> ** 10^18` | 0.042s | 0.043s | 0.98x | 7,760 B | | `crt` | `1,000,000` `std.math.crt` calls | 0.068s | 0.080s | 0.86x | 6,508 B | | `comb` | `Comb(2_000_000)` + `5,000,000` `choose` queries | 0.081s | 0.071s | 1.15x | 10,132 B | Aggregate: **p50 = 0.97x**, **max = 1.15x** (targets: `<= 1.1x` p50, `<= 1.5x` max). Every emitted file is 8–25% of the 64 KB judge ceiling. Profiling history is in `research/frictions/bench-math.md`. --- # Round 5: operation values and range structures URL: /docs/ref/lib/ops-ranges Normative text from [spec/lib/ops-ranges.md](https://github.com/ryanbai1412/cp-lang/blob/main/spec/lib/ops-ranges.md). Built on rounds 1 to 4: ranges are `Range` over a domain, cuts are `D.cuts`, trees expose `t.Pre`, and parameters ask for the weakest capability they use. This doc proposes how an operation is written as a value, how its laws are stated, and one vocabulary for every structure that folds or updates ranges. ## The model in one paragraph An **operation value** is a value whose type implements `Op`, `Monoid` or `Group`. `+`, `max`, `gcd` and `Monoid(id: e, op: f)` are all operation values. **Laws** (`Commutative`, `Idempotent`, `Selective`) are traits with no methods, implemented by the operation's type as a promise. An **action** is a monoid of tags plus how one tag changes a folded value. An **order** is a key fn (`by:`), and a **semiring** is two ops. Sequence folds, fast powers, matrices, convolutions, tree DP and Dijkstra take these same values. Every range structure takes operation values and offers only the methods its operations support. It picks a faster strategy when a law holds, but only one that is never worse (the algorithm and its answers stay the same). `cpl explain` shows which strategy it picked. **You name the structure; the laws pick its strategy.** ```cp var st = SegTree(max, a) // point set, range max var lz = SegTree(+, a, act: add) // range add, range sum (lazy) var mx = SegTree(max, a, act: add) // range add, range max: no push-down var du = SegTree(act: assign, a) // range assign, point read (dual) let sp = SparseTable(min, a) // O(1) fold: overlapping halves let fw = Fenwick(a) // prefix and range sums let ps = Prefix(a) // static: O(1) range sums ``` ## 1. Operations ### The traits ```cp pub trait Op: fn op(self, a: T, b: T) -> T law assoc(a: T, b: T, c: T) = op(op(a, b), c) == op(a, op(b, c)) pub trait Monoid = Op + HasId pub trait HasId: @get fn id(self) -> T law ident(a: T) = op(id, a) == a and op(a, id) == a pub trait Group = Monoid + HasInv pub trait HasInv: fn inv(self, a: T) -> T law inverse(a: T) = op(a, inv(a)) == id pub trait Commutative: Op // op(a, b) == op(b, a) pub trait Idempotent: Op // op(a, a) == a pub trait Selective: Idempotent // op(a, b) is a or b ``` `op(a, b)` puts `a` on the left. Every fold runs left to right in domain order, so a non-commutative operation (matrix product, string concat, affine composition) just works. ### Built-in operation values | Value | Implements | Identity | |---|---|---| | `+` | `Group`, `Commutative` | `T.zero` | | `*` | `Monoid`, `Commutative`; `Group` on `Mod

` without zero | `T.one` | | `^` | `Group` (`inv` is itself), `Commutative` | `0` | | `\|`, `&` | `Monoid`, `Commutative`, `Idempotent` | `0`, all bits | | `min`, `max` | `Monoid`, `Commutative`, `Selective` | far end of `T`; `None` on `?T` | | `gcd` | `Monoid`, `Commutative`, `Idempotent` | `0` | | `and`, `or` | `Monoid`, `Commutative`, `Selective` | `true`, `false` | A bounded `Int` (`0..=1e9`) has a far end, so `min` and `max` are monoids on it with no sentinel. An unbounded `Int` has no far end, so `min` on it is only an `Op`: structures over it still build, and their folds return `?Int` (section 2). ### Your own operation Inline, for the common case with no extra laws: ```cp let lo = Monoid(id: Low.empty, op: (a, b) => a.join(b)) let cat = Op((a: Str, b: Str) => a + b) // no identity: a semigroup ``` With laws, as a named type. The `impl` with no body states a law. It is a promise: `cpl stress` samples it and `laws_hold` tests it (the `law` tier in 05-ownership.md). ```cp struct Lcm impl Monoid for Lcm: @get fn id(self) = 1 fn op(self, a, b) = lcm(a, b) impl Commutative for Lcm impl Idempotent for Lcm ``` Or adding a law to an inline value with a wrapper. These are plain library fns returning wrapper types, so user libraries can write more of them: ```cp let lo = Monoid(id: Low.empty, op: join).commutative() ``` A record type can also be its own operation by implementing `Add`. `SegTree(+, a)` over `[D]MaxSub` then uses `MaxSub.empty()` as the identity and `+`. Nothing special is needed, because `+` is generic over `T: Add`. ## 2. Combining operations Bigger operations are built from smaller ones with plain library fns, so no summary needs a hand-written struct unless it carries real logic. | Form | Meaning | Laws kept | |---|---|---| | `each(+, max)`, `each(s: +, hi: max)` | one op per component, on tuples or records | those all parts share | | `op.rev()` | `(a, b) => op(b, a)` | all | | `op.opt()` | the op on `?T`, `None` as identity: any `Op` becomes a `Monoid` | all | | `Monoid(id:, op:)`, `Group(id:, op:, inv:)` | from lambdas | none until stated | | `.commutative()`, `.idempotent()` | state a law on an inline value | adds it | ```cp var st = SegTree(each(+, max, min), a.map(x => (x, x, x))) // sum, max, min at once let (s, hi, lo) = st.fold(l..r) var nm = SegTree(each(sum: +, hi: max), a.map(x => (sum: x, hi: x))) nm.fold(l..r).hi ``` `each` is named, not a bare tuple `(+, max)`, because `(max, +)` already reads as a semiring in CP writing. A tuple of ops is a compile error that suggests `each(...)` or `Semiring(...)`, so neither meaning is implied. **Summaries with real logic stay named library types**, each one an `Add` (or `Op`) impl plus a constructor from one element: `MaxSub` (best subarray), `MinCount`/`MaxCount` (extreme and multiplicity), `Affine` (composition of `a x + b`), `Hash` (polynomial string hash, a `Group`), and `Mat` under a semiring. `MinIdx`/`MaxIdx` go: `min(by:)` keeps the left operand on ties, so it already returns the first minimum (section 3). **Reversal.** A fold along a path goes one way up and the other way down. That is free for a `Commutative` op. Otherwise the value type implements `Reversible` (`x.rev()`: the fold of the same elements read backwards), as `MaxSub` and `Hash` do. `fold_path` requires one of the two; asking without either is a compile error naming both fixes. **An `Op` without an identity** still builds every structure; its folds return `?T`, `None` for an empty range. The `?` is in the return type, so it is visible, and it is exactly `op.opt()`. ## 3. Orders An order is the other operation value every contest program passes around: `sort`, `min`/`max`/`argmax`, heaps, ordered sets, `bsearch` over sorted data and Dijkstra all take one. One trait and one argument cover them all. ```cp pub trait Ord: fn cmp(self, b: Self) -> Ordering law total(a, b, c) = ... // antisymmetric, transitive, total ``` - Ints, floats (NaN traps in debug), `Str` and `Bool` are `Ord`; `?T` is not (chapter 2): sort optionals with a key such as `by: x => (x == None, x ?? 0)`. Tuples and records derive it lexicographically in field order. - **`by:` takes a key fn**, and that is the one way to pass an order: `sort(mut es, by: .w)`, `argmax(a, by: x => x.score)`, `Heap(by: .d)`. Omitted, it is the element's own `Ord`. - **Descending is `desc(k)`** on the key (exists in `algebra.cp`), so a mixed order is one tuple: `by: e => (e.w, desc(e.name))`. A bare `desc` reverses the whole order: `sort(mut a, by: desc)`. - **No comparator argument.** An order a key can't express (fractions compared by cross-multiplying, polar angle) is a small type with `impl Ord`, used as the key: `by: p => Angle(p)`. Then the order has a name, gets the `total` law sampled by stress, and works in every API. - Every sort is stable; ties keep input order. `min`, `argmin` and the others return the **first** of equal keys, `max` and `argmax` too. ### Orders make `min` and `max` monoids A total order is exactly what makes `min` and `max` `Selective` (section 1). So `min(by: k)` and `max(by: k)` are operation values too, and one order serves both sorting and folding: ```cp let lightest = min(by: .w) // an Op on edges: keeps the lighter var seg = SegTree(lightest, es) // range "lightest edge" let best = es.fold(max(by: e => (e.w, desc(e.id)))) ``` The identity is `None` on `?T` or the far end of a bounded key, the same as plain `min`. Ties keep the left operand, which matches "first of equal keys" above, so a segment tree of `min(by:)` returns the leftmost minimum with no index trick (this replaces `MinIdx`/`MaxIdx`). ### Heaps `Heap(by:)` pops the smallest key; `Heap(by: desc)` pops the largest. This replaces the `MinHeap`/`MaxHeap` pairs (and the erasable, indexed and meldable pairs) with one type each: `Heap`, `ErasableHeap`, `IndexedHeap`, `MeldHeap`. `MinMaxHeap` stays, since it pops both ends. `MinHeap` and `MaxHeap` remain as type aliases for `Heap()` and `Heap(by: desc)`, since they are what everyone searches for; `cpl fmt` leaves them alone. ### Dijkstra: a monoid and an order A shortest-path search needs two things from weights: how a path's cost grows by one arc, and which of two costs is better. That is a `Monoid` and an `Ord`, the same two concepts: ```cp pub fn dijkstra, M: Monoid = Plus>( g: G, from: Seq<(V, W)>, step: M = +, until: ?V = None, ) -> Paths ``` ```cp dijkstra(g, from: [(s, 0)]) // sum of weights dijkstra(g, from: [(s, 0)], step: max) // bottleneck path dijkstra(g.weighted(a => (a.w, 1)), from: [(s, (0, 0))]) // cost, then hops ``` - Correctness needs one law: extending a path never makes it better, `step(d, w) >= d`. That replaces "traps on a negative weight": debug builds check it on each relaxation and name the arc that broke it. - Tuples add field-wise and compare lexicographically, so `(cost, hops)` needs nothing new. - `bfs01`, `dial` and `bellman_ford` take the same `step:`. Floyd–Warshall takes `step:` too; it needs `Commutative` only when the graph is undirected. ## 4. Actions An action is a monoid of tags (`F`) plus `apply`, which says what a tag does to a folded value of `n` leaves. Tags compose **in time order**, `tags.op(old, new)`, the same left-to-right rule as values, so there is no separate `compose(new, old)` convention to get backwards. ```cp pub trait Action: // M is the fold op's type, e.g. type of `+` type Tags: Monoid @get fn tags(self) -> Self.Tags fn apply(self, f: F, x: M.T, n: Int) -> M.T law hom(f, a, b) = apply(f, op(a, b), 2) == op(apply(f, a, 1), apply(f, b, 1)) law comp(f, g, x) = apply(tags.op(f, g), x, 1) == apply(g, apply(f, x, 1), 1) ``` **Stock actions are generic over the fold op**, so one name works on every fold it makes sense for, and the pairing is checked: | Action | On `+` | On `min` / `max` | On other ops | |---|---|---|---| | `add` | `x + f * n` | `x + f` | error: no `impl` | | `assign` | `f * n` | `f` | `f` folded `n` times with `op` (O(log n)) | | `affine` | `a * x + b * n` | error: not monotone | error | | `flip` | swaps `now` / `flipped` of a `Flip` | same | same | `SegTree(gcd, a, act: add)` is a compile error, `add does not act on gcd`, not a wrong answer. Today's combined names (`AddMax`, `AddSum`, `AssignMin`) become `SegTree(max, act: add)` and so on. A custom action, written inline: ```cp let shift = Action(tags: +, apply: (d, l: Low, n) => (..l, cover: l.cover + d)) var low = SegTree(Low.join, [Cut] c => Low(0, c, c, 0), act: shift) ``` `n` is computed from the node, never stored, so an action that ignores it costs nothing extra. A lambda that takes `(f, x)` without `n` is accepted. ## 5. Semirings Two ops, where `mul` distributes over `add`: what matrix products, path algebras and convolutions are generic over. ```cp pub trait Semiring: type Add: Monoid + Commutative type Mul: Monoid law distrib(a, b, c) = mul(a, add(b, c)) == add(mul(a, b), mul(a, c)) law absorb(a) = mul(add.id, a) == add.id Semiring(+, *) // counting; the default for numbers Semiring(min, +) // shortest paths (tropical) Semiring(max, +) // longest paths, best scores Semiring(or, and) // reachability Semiring(max, min) // bottleneck ``` The pair is written with the ops themselves, so the names `min_plus`/`max_plus`/`bool_ring` go. Every number type is a `Semiring(+, *)` by default, so `over:` is only ever written for the others. ```cp let m = Mat(over: Semiring(min, +), d) // d: [V, V]?Int let k_steps = pow(m, k) // shortest walk of exactly k arcs let ways = pow(Mat(adj), k) // number of walks: (+, *) ``` - `Mat(over: S)` multiplies under `S`; `m * m2` is `S.mul`-of-`S.add`. `det`, `inverse` and `rank` need a field (`Mod

`, `F64`), and exist only then. - Floyd–Warshall is the closure of a `(min, +)`-like semiring: `step:` is its `mul`, `min(by:)` its `add`. ## 6. Folds on plain sequences The same values fold any `Seq`, with no structure: | Form | Meaning | Cost | |---|---|---| | `xs.fold(op)` | left to right; `T` for a `Monoid`, `?T` for an `Op` | O(n) | | `xs.sum()`, `xs.prod()` | `fold(+)`, `fold(*)` | O(n) | | `xs.min()`, `xs.max()`, `xs.min(by:)` | `fold(min)` and friends; `?T`, `None` when empty | O(n) | | `xs.scan(op)` | the running folds, lazily: a generator | O(1) per item | | `pow(x, k, op = *)` | `x` folded with itself `k` times by squaring | O(log k) ops | `pow` is the one fast power: numbers, `Mod

`, matrices under any semiring, permutations (`op: compose`), `Affine` maps, and any user monoid. `k = 0` needs a `Monoid`; an `Op` traps on it. ```cp let f = pow(Affine(a, b), k, op: then) // apply x -> a x + b, k times let p = pow(perm, 1e18, op: compose) // a permutation applied 10^18 times ``` ## 7. One vocabulary for range structures Every range structure uses these names, and has a method only when its operations support it: | Form | Meaning | Needs | |---|---|---| | `S(op, a)` | build from `[D]T`; `D` comes from `a` | | | `S(op, fill: x)`, `S(op, [D] i => ...)` | build filled, or from a fn | | | `s[i]` | the value at `i` | | | `s[i] = x`, `s[i] += y` | point write, through a `lends mut` place | point updates | | `s.fold(r)` | fold of `Range` `r`, left to right | `T` for a `Monoid`, `?T` for an `Op` | | `s.all` | fold of everything, O(1) | `Monoid` | | `s.prefix(c)` | fold of everything before cut `c` | | | `s.apply(r, f)`, `s.apply_all(f)` | apply tag `f` to every position in `r` | `act:` | | `s.right_while(from: c, ok)` | the last cut `d` with `ok(s.fold(c..d))`, `ok` monotone | `Monoid` | | `s.left_while(to: c, ok)` | the first cut `d` with `ok(s.fold(d..c))` | `Monoid` | | `s.clear()` | every leaf back to `fill` (or the identity), pending tags dropped, O(n) | | | `for (i, x) in s.items` | every position and value, O(n) | | - `right_while` and `left_while` return cuts, like `bsearch` in round 1. They replace `max_right` and `min_left`. - `fold`, `apply` and `[]` take `Range` and `D`, so `t.sub(v)` on a `[t.Pre]` tree and `..=lo.l` on a `[Rank.cuts]` tree just work. - `t.fold_path(a, b, s)` and `t.apply_path(a, b, s, f)` from round 4 work on any structure that has `fold` and `apply`. ## 8. The structures | Job | Structure | Build | Query | Strategy picked by laws | |---|---|---|---|---| | point write, range fold | `SegTree(op, a)` | O(n) | O(log n) | | | range apply, range fold | `SegTree(op, a, act:)` | O(n) | O(log n) | tags `Commutative`: no push-down | | range apply, point read | `SegTree(act:, a)` | O(n) | O(log n) | tags `Commutative`: no push-down | | static fold | `SparseTable(op, a)` | O(n log n) | O(1) | `Idempotent`: overlapping halves; else `DisjointSparseTable(op, a)` | | static prefix / range sum | `Prefix(a)` | O(n) | O(1) | `+` only: `prefix(c)`, `sum(r)`; other ops scan with `a.scan(op)` | | dynamic prefix / range sum | `Fenwick(a)` | O(n) | O(log n) | `+`/`-` only: `sum(r)`; other ops use `SegTree` | | sliding window fold | `Window(op)` | | O(1) amortized | `Selective`: monotone deque; else two stacks | | offline range add | `Diff` | | O(1) per `add(r, x)`, O(n) finish | `+`/`-` only | | old versions | `PersistentSegTree(op, a)`, `PersistentLazySegTree(op, a, act:)` | O(n) | O(log n) | as `SegTree` | | huge index range | `SegTree(op, over: lo..hi)` | O(1) | O(log range) | nodes made on first touch | | chmin/chmax with sums | `BeatsSegTree(a)` | O(n) | O(log² n) amortized | its own structure | **What merges:** - `LazySegTree` and `DualSegTree` become `SegTree` with `act:`. - `DisjointSparseTable` stays its own type: `SparseTable` needs `Idempotent`. - `GroupFenwick`, `PrefixFenwick` and `XorFenwick` become `Fenwick`. - `RangeFenwick` goes: range add with range sum is `SegTree(+, a, act: add)`, iterative and without push-down since `add` tags commute. `Fenwick` takes no `act:`. - `MonoDeque`, `WindowFold` and `sliding_fold` become `Window`. - `SparseSegTree` and `SparseLazySegTree` become `SegTree(over:)`. - `AddMax` and the other combined action names become `act: add` and the other stock actions. **What stays named, because it's a different structure:** `Fenwick` (half the memory of a `SegTree`, and faster), `SparseTable`, `PersistentSegTree`, `BeatsSegTree`, the 2D forms, `WaveletMatrix` and `MergeSortTree`. **Why `act:` and not a separate `LazySegTree`:** the structure is determined by what you hand it: an op, an action, or both. The cost is still visible. `act:` in the constructor is where tag memory appears, and `cpl explain` shows the layout. `Fenwick2D` is point add and rectangle sum over a grid (O(log R log C)); `Line(k, m)` is the `k x + m` that `LiChao` and `MonotoneHull` store. ## 9. Specialization Ryan's example is that lazy propagation is unnecessary when tags commute. **Without push-down.** If the tags' monoid is `Commutative` (`add` on `max`, `add` on `+`, `xor` flips), the order in which a node's ancestors' tags apply doesn't matter. - `apply(r, f)` leaves `f` on the O(log n) covering nodes and updates the folds on their ancestors. - `fold(r)` adds up the tags on each covering node's path from the root as it climbs. - Nothing is ever pushed down. That is about half the memory traffic of a propagating tree, with the same O(log n) bound and the same answers. - A point write `s[i] = x` still pushes along its one path, O(log n). **How a library writes it.** A generic body can test a bound, and the test is decided when the fn is instantiated: ```cp pub fn apply(mut self, r: Range, f: F): if A.Tags: Commutative: self.mark(r, f) // no push else: self.push_path(r) self.mark(r, f) ``` - `if T: Trait` is a compile-time test on a type. - Each branch is checked with the bound it assumes. - The branch not taken is never emitted. This is a new power for user libraries too (POWERS W10b). It replaces duplicate structures with one body. **Rules that keep specialization honest:** 1. **It majorizes.** A law may choose a strategy that is never worse in time or memory, and has the same answers on lawful inputs. A law never changes the complexity class you were promised, and it never switches to a different named structure. 2. **Visible.** `cpl explain` shows "SegTree: tags commute (add on max), no push-down". 3. **Laws are promises.** A wrong `impl Commutative` gives wrong answers, never undefined behaviour. Stress runs sample every promised law on random inputs and say which one failed. `--laws=off` turns the specializations off, so you can compare. 4. **Missing laws are errors, not silent wrongness.** `t.fold_path` with a non-`Commutative` op whose `T` doesn't implement `Reversible` is a compile error. Today it silently assumes "its own reverse". `Fenwick` is `+`-only; any other op is an error that suggests `SegTree`. ## 10. Groups: subtract instead of store An inverse turns "fold of `l..r`" into "fold up to `r` minus fold up to `l`". Every structure that can use this, does, under the same rule: the method exists when the op is a `Group`. | Structure | With a `Group` | |---|---| | `Prefix(a)` (`+` only) | `sum(r)` in O(1) | | `Fenwick(a)` (`+` only) | `sum(r)` in O(log n); `s[i] = x` (read, then add the difference) | | `Window(op)` | `pop()` subtracts: O(1) worst case, no second stack | | `Diff` (`+` only) | `add(r, x)` offline in O(1), then `finish()` in O(n) | | `Potentials(op)` | union-find with relative values (below) | **Union-find with potentials.** "Value of `b` is value of `a` plus `w`" constraints, checked online, are a `Group` on a DSU: ```cp var p = Potentials(+) if not p.relate(a, b, w): print("CONTRADICTION") // val[b] = val[a] + w p.diff(a, b) // ?Int: val[b] - val[a], None if unrelated ``` It works for any group: `^` for parity constraints, `Affine` for "`b = 2a + 3`" problems, permutations for orientation puzzles. The existing `DsuOf(join:)` stays for per-set summaries; its `join` is an `Op`. **Shared undo.** `Dsu`, `DsuOf`, `Potentials`, `Window` and the persistent structures that support stepping back share one pair: `mark() -> Mark` and `undo_to(m)`. Rollback Mo and offline dynamic connectivity take any structure with that pair. ## 11. Offline and sqrt structures - **Mo's algorithm keeps closures, not op values.** Mo exists for answers that are not decomposable folds (distinct count, mode); with a monoid you would use a segment tree. Its signature stays `mo(queries, add:, remove:, answer:)`, with `order: .hilbert` as an option instead of a second fn. Rollback Mo is `mo(queries, add:, keep: s)` where `s` has `mark`/`undo_to`, so no `remove` is needed. - **Sqrt blocks** are `Blocks(op, a, act:, size:)` with exactly the `SegTree` vocabulary. They exist for operations with no cheap composition (e.g. "sort this block", rebuild per block) and for the O(1)-update, O(sqrt n)-query trade. - **Offline divide and conquer over time** (`timetree.cp`) takes any structure with `mark`/`undo_to`. ## 12. Trees and DP Every tree and DP facility takes the same values: | Facility | Takes | Needs | |---|---|---| | `t.fold_path(a, b, s)` | any structure with `fold` over `t.Pre` | `Commutative` or `Reversible` | | `t.up(op, lift:, finish:)` | children folded with `op` | `Monoid` | | `t.reroot(op, lift:, finish:)` | same, every root | `Monoid` (no inverse: prefix and suffix folds) | | `Lift(t, val, op)` | binary lifting of path folds | `Op`; non-commutative needs `Reversible` | | `LiChao(min, over:)` | lower envelope of lines | a `Selective` op (`min`, `max`, `min(by:)`) | | `Window(op)` | sliding window fold, monotone queue | `Selective` for the deque strategy | | `dijkstra(step:)` | path cost growth | `Monoid` + `Ord` on `W` | `Lift` changes from `(op, identity)` lambdas to one op value. `LiChao`'s `pick` becomes the same selective op used everywhere, so `min(by: c => (c.cost, c.used))` breaks ties with no special support. ## 13. Convolutions One fn, two choices: how indices combine, and which semiring values live in. ```cp convolve(a, b) // c[i + j] += a[i] * b[j] convolve(a, b, on: ^) // c[i ^ j] (Walsh–Hadamard) convolve(a, b, on: |) // c[i | j] (subset-sum transform) convolve(a, b, on: &) // c[i & j] convolve(a, b, on: subset) // i | j with i & j == 0 convolve(a, b, on: gcd) // c[gcd(i, j)] (Dirichlet-style) convolve(a, b, over: Semiring(max, +), concave: .b) // max-plus, b concave ``` - The index op is an operation value (`on:`), so the eight `convolve_or`/`_and`/`_xor`/... names collapse to one (done in 0.3.0; `std.ntt`). - The value type picks the algorithm, which is visible in its type: `Mod

` with an NTT prime uses NTT; any other `Mod` or `Int` uses three primes and CRT; `F64` uses FFT. `cpl explain` names it. - `over:` other than `Semiring(+, *)` has no fast transform in general, so it requires a stated shape (`concave: .b` gives the O(n log n) SMAWK path; debug checks the shape). Without one it is an error, not a hidden O(n²). - `cyclic: true`, and `convolve_all(polys)` for many at once, stay. ## 14. Cost model What a contestant can rely on, matching goal 3 (abstractions cost what C++ costs): - **Operation values are free.** `+`, `max`, `gcd` are zero-size values of their own types. A structure is monomorphized on the op's type, so the op is inlined into the loop: no function pointers, no virtual calls. A lambda passed to `Monoid(id:, op:)` is also a distinct type and inlines the same way. - **Identities are constants** when the op's type knows them (`T.zero`, the far end of `T`), and one stored field otherwise. They are never stored per node. - **Spans are computed, not stored.** The node's span `n` comes from its level in a power-of-two layout. An action that ignores `n` costs nothing. - **Tags cost memory only with `act:`**: one `F` per internal node, plus one bit per node for "has a tag" only when `F` has no spare value for "no tag" (a niche, as for `?T`). - **Laws cost nothing at run time.** They select code at compile time; only stress and debug-mode checks evaluate them. - `cpl explain` on a structure prints its layout, bytes per element, and each strategy chosen and why. ## 15. Testing laws A law is a promise; the tools make it cheap to check: - `laws_hold(op, samples)` evaluates every law the value promises on sampled inputs and returns the first failure: `"Lcm breaks assoc at (4, 6, 10)"`. - `cpl stress` samples the laws of every op and action used in the run, drawing inputs from the values that actually flow through the structure, so a law that fails only on real data is found too. - `--laws=off` disables every law-driven strategy, so a wrong answer that disappears with it is a broken promise, not a broken algorithm. - Debug builds check the laws that are cheap per operation: Dijkstra's `step(d, w) >= d`, `Ord`'s antisymmetry on the compared pair. ## 16. Examples from the dreams ```cp // cf2096f: range add, range min, test for zero var cover = SegTree(min, fill: 0, act: add) cover.apply(s.a..=s.b, 1) if cover.fold(s.a..=s.b) == 0: ... // cf2152g: flip a subtree, read the root var st = SegTree(Side.join, t.reorder(init), act: flip) st.apply(t.sub(v), true) print(st.all.now.ends) // cf2084f: a custom monoid, prefix and suffix folds var st = SegTree(Monoid(id: edge, op: op)) out[v] = if below: st.fold(..=v) else: st.fold(v..) // window minimum var w = Window(min) for i in I: w.push(a[i]) if w.len > k: w.pop() ans[i] = w.all! ``` ## 17. What this needs from core - Trait aliases and associated types (W10a, already accepted). - Bodiless `impl` as a law promise (exists for field traits, W10a). - `if T: Trait` compile-time tests in generic bodies (new, W10b). - A type's far end (`T.max`, `T.min`) for bounded types (round 1). - Operator values having their own types (`+` is a value of type `Plus`), so `impl Action for Add` can pair actions with folds. ## Open 1. **`convolve(on:)` for `subset`.** `subset` is not an operator, so it is a named index op the library defines. That is fine as long as user libraries can define more (they can: it's a value with a transform impl). Settled in review: no `act:` on `Fenwick` (range add/sum is a `SegTree`), `MaxHeap` as an alias, `each(...)` for products of ops. --- # Random inputs, alternatives and checkers URL: /docs/ref/lib/random-stress Normative text from [spec/lib/random-stress.md](https://github.com/ryanbai1412/cp-lang/blob/main/spec/lib/random-stress.md). Status: draft for 0.3.0. `std.rand` and the stress roles. Sources: archived `design/spec/30-stress.md`, `plan/50-debugging.md`; decision 146 for laws. The tool that drives them is `tools/stress.md`. ## Randomness - `Rng(seed)` is a deterministic splitmix64 stream. `rng.int(lo, hi)` (both ends inclusive), `rng.float()`, `rng.pick(xs)`, `rng.shuffle(mut xs)`, `rng.perm(D)`. There is no time-seeded `Rng`: programs that need randomness on the judge pass a seed they choose, so every run replays. - Hashing salts (`HashMap`, string hashing) are fixed per build profile, not drawn from an `Rng`. ## Typed generators `gen(...)` generates any `Read` type within its contract, so the reads are the input spec: ``` gen(1..=8) // an Int gen<[V]1..=1e9>() // an array over a fresh domain gen(len: 1..=10) gen>(simple: true, connected: true) gen>(shape: random) // also path, star, caterpillar, binary gen>() ``` - Constraints types cannot state go in `@gen fn input()`, which prints the input exactly as the judge would, using `gen` calls. - Every `gen` choice is recorded, so the shrinker minimizes any failing case without a per-problem shrinker: it shortens collections, lowers numbers toward their range's low end, and removes edges, keeping only inputs that still satisfy every read contract. - Sizes come from `with stress(max_size: ..., time: ...)` or the caps on an `@alt`. ## Alternatives ``` @alt(count, n: ..=8) fn count_slow(xs: List) -> Int: ... @alt(program, n: ..=10) // a whole-program brute fn brute(): ... ``` - `@alt(f, caps)` marks another implementation of `f`; stress compares them on generated inputs. Inside the alt, a cap refines the capped value's type (`n: 1..=8`). - An alt of a nested function is substituted at the real call sites during whole-program stress, so its preconditions hold; stressing it alone needs its own `@gen`. - Alts are stripped from submissions. ## Checkers - A relation `check: (input, ours, theirs) => Bool` on an `@alt`; equality is the default. - A unary `@check fn ok(input: In, out: Reader) -> Bool` runs on every implementation's output, for problems with many valid answers. Pair it with a brute that compares feasibility, since a unary checker cannot catch a wrong "impossible". - Floats compare with `close(a, b, abs:, rel:)`. ## Interactors `@interactor fn judge(w: Wire)` is the other end of the pipes for an interactive problem; `cpl stress` and `cpl interact` run the program against it with generated hidden data. ## Laws `laws_hold(op, samples)` checks a value's declared laws; stress samples laws of every operation value the program builds (`lib/ops-ranges.md`). --- # Round 3: search and DP URL: /docs/ref/lib/search-dp Normative text from [spec/lib/search-dp.md](https://github.com/ryanbai1412/cp-lang/blob/main/spec/lib/search-dp.md). Built on rounds 1 and 2: ranges have cut ends, binary search is a range method, folds over `.keys` give positions, `scan` is indexed by cuts. ## The model in one paragraph A DP is a table over the domains its state lives in, filled in an order the code states, so the table type says what a state is: `[Pos.cuts]Int` for a prefix DP, `[V.ranges]Int` for an interval DP, `[B.subsets]Int` for a mask DP, `[V, K]?Int` for "best at v using k". Updates are `min=` / `max=`, which return whether they improved, so reconstruction is one more line. Top-down is `@memo(array) fn` (a dense table over the parameter types) or `@memo(map) fn` (a hash map over the states visited); you pick, since neither is better on every axis. The named speed-ups (D&C, Knuth, SMAWK, convex hull, aliens, slope trick) are library functions that take the same cost function the plain DP uses, so switching is a local edit. ## Search Binary search lives on ranges (round 1). This round adds the rest. | Form | Meaning | Cost | |---|---|---| | `r.first_true(ok)`, `r.last_true(ok)`, `r.bsearch(ok, last:)` | round 1 | O(log n) calls | | `r.first_true(ok, near: c)` | galloping search from cut `c` outward: cost grows with the distance to the answer | O(log d) calls | | `r.peak(by: f)`, `r.valley(by: f)` | an argmax / argmin of `f` unimodal on `r`, `?D`; first on plateaus that don't hide the peak | O(log n) calls | | `(lo..hi).bsearch(ok, steps: 100)` with `F64` ends | the flip point of a real predicate | `steps` calls | | `(lo..hi).peak(by: f, steps: 100)`, `.valley(...)` | real ternary / golden-section search, `F64` | `steps` calls | | `parallel_bsearch(qs, r, apply, ok)` | every query's `first_true` over shared monotone updates `r` | O((q + \|r\|) log \|r\|) | | `dinkelbach(solve, lo)` | max ratio: `solve(λ)` returns the best `(num, den)` at `λ` | O(log) solves | `F64` ends make an **interval**: `x in i`, `i.l`, `i.r`, `i.mid`, `bsearch`, `peak`, `valley`. It has no elements, so no `for`, `len` or `first_true`. The default `steps: 100` shrinks a 1e18 span below 1e-12. The answer-search idiom is just the range method, read as the statement: ```cp let t = (0..=1e18).first_true(t => can_finish(by: t))! // smallest feasible time let k = (1..=n).last_true(k => fits(k)) ?? 0 // largest k that fits, 0 if None ``` Over reals the searches take a step count instead of an integer range: `bsearch_real(lo, hi, ok, steps:)` is the least `x` with `ok(x)` to within `(hi - lo) / 2^steps`, and `ternary_min_real(lo, hi, f, steps:)` and `ternary_max_real` find the optimum of a unimodal `f` by golden section. Each costs `steps` calls. ## Tables ```cp domain Pos = 0..n var dp: [Pos.cuts]Int = inf // prefix DP: dp[c] is the best for a[..c] dp[0] = 0 for i in Pos.cuts: for j in ..i: // every earlier cut; j..i is the piece a[j..i] dp[i] min= dp[j] + cost(j..i) ``` - **The table's index type is the state.** `[V, K]?Int` for "best at v with k", `[Pos.cuts]` for prefixes, `[V.ranges]` for pieces, `[B.subsets]` for masks. A wrong-order index is a type error. - **Unreached is `None`, not a sentinel.** `?Int` tables start `None`; `x min= y` on `None` takes `y`, and `x min= None` does nothing, so impossible states never need `inf` guards. `inf` exists for `Int` tables when you'd rather; adding to it is an overflow error in debug. - **`min=` / `max=` return whether they improved**, so the argmin is kept where it's found: ```cp if dp[i] min= dp[j] + cost(j..i): from[i] = j ``` - **Layers.** A DP over k layers keeps two tables and moves: `repeat k - 1: best = layer(best)`. Assigning a returned table is O(1). - **Reconstruction** walks the kept argmins: `for c in from.chain(Pos.cuts.last!)` yields `c, from[c], from[from[c]], ...` until `None`. `chain` is an `[D]?D` method (any parent array: DP choices, BFS back pointers, DSU). ### Interval DP: `V.ranges` `V.ranges` is the domain of all non-empty ranges of `V`, stored as a triangle (n(n+1)/2 slots). Iterating it goes by length, then left end, so a piece comes after all its sub-pieces. `r.splits` yields every way to cut `r` into two non-empty pieces, as `(left, right)` with `left.r == right.l`: one pair per cut strictly inside `r`, so `len - 1` of them, none for one element. O(1) to make, nothing allocated; the cut itself is `left.r`. A `Range` goes wherever a `V.ranges` is expected, the way an `Int` goes into a range-typed slot: non-emptiness is a contract, proved when it can be and checked in checked builds otherwise, so `best(r.first!.next!..=r.last!)` needs no conversion. ```cp var dp: [V.ranges]Int = 0 // merging stones, matrix chain, ... for r in V.ranges if r.len >= 2: dp[r] = r.splits.map((x, y) => dp[x] + dp[y]).min()! + w(r) print(dp[V.range]) ``` ### Mask DP: `B.subsets` `B.subsets` (written `Subset`) is the domain of subsets of a small domain `B` (at most 64 members, one `U64`): set algebra `s | t`, `s & t`, `s - t`, `b in s`, `s.len`, and generators `s.subsets` (submasks, `s` first, empty last) and `s.supersets`. ```cp var best: [Group.subsets]?Int = None best[{}] = 0 for s in Group.subsets: for g in s.subsets if g != {}: best[s] max= score[g] + best[s - g] ``` `a.fold_subsets(op)` / `a.fold_supersets(op)` over `[B.subsets]T` are the sum-over-subsets transforms, O(2^n · n); with `op` inverse, `unfold_*`. ### Top-down: `@memo fn` ```cp @memo(array) fn ways(i: Pos.cuts, tight: Bool, sum: 0..=9 * 18) -> Mod: if i == Pos.cuts.last!: return Mod(sum % k == 0) let hi = if tight: digit[i.r!] else: 9 (0..=hi).map(d => ways(i.next!, tight and d == hi, sum + d)).sum() ``` - **The storage is spelled, never picked for you.** `@memo(array)` is a dense table: every parameter must be a domain, `Bool`, enum or ranged Int, else it's a compile error naming the parameter. Memory is the product of the sizes (here 19 × 2 × 163 slots), allocated when the enclosing block starts; `cpl explain` prints it. `@memo(map)` is a hash map over any hashable arguments: O(states visited) memory, a hash per call. - **Bare `@memo` is an error** whose fix offers `array` when every parameter is bounded and `map` otherwise. An array spends memory on states the recursion never reaches and a map pays a hash per call, so neither majorizes and the choice is the contestant's. - `@memo(into: dp)` names an existing `var dp: [..]?T` as the table, so the same cache can be read after the recursion (reconstruction, answers over every state). - Recursion depth follows the judge profile's stack; `@memo` adds nothing per frame beyond the call. - `ways.clear()` empties the cache (multitest). ## Speed-ups: same cost function, one edit Each takes the `cost` the plain DP calls, so the plain version stays the brute in `cpl stress`. | Form | Plain DP it replaces | Cost | |---|---|---| | `monotone_minima(rows, cols, f)` | `row i: min over c of f(i, c)`, argmin monotone in `i` (D&C opt) → `[R]?(val, at)` | O((n + m) log n) calls | | `smawk(rows, cols, f)` | same, `f` totally monotone (Monge) | O(n + m) calls | | `knuth(n, cost)` | `dp[i][j] = min over splits + cost(i, j)` with Knuth's condition → `(n + 1)²` table | O(n²) | | `split_best(groups, range:, best:)` | values of a family of ranges, best first: each pop re-queues the two pieces around the chosen position (k largest subarray sums) | O(k log(n + k)) `best` calls | | `aliens(k, solve)` | "exactly k items" when the value is convex in k: `solve(λ)` returns `(val, count)` | O(log range) solves | | `monge_path(n, cost)` | shortest 0 → n path with Monge `cost(j..i)` (LARSCH) | O(n log n) | | `LiChao(max, over: r)`, `.add(line, on:)`, `.at(x)` | max of lines / segments at x | O(log \|r\|) | | `LineContainer(max)` | max of lines, any order | O(log n) | | `MonotoneHull(max)` | lines and queries both monotone | O(1) amortized | | `convolve(a, b, over: Semiring(min, +), shape:)` | `c[k] = min a[i] + b[k - i]` | O(n + m) or O(n m) by shape | | `Concave`, `Convex` (std.slope, decision 81) | piecewise-linear concave / convex DP | O(log n) per op | D&C optimisation as a library call, the same layer cf868f writes by hand: ```cp fn layer(prev: [Cut]?Int) -> [Cut]?Int = monotone_minima(Cut.range, Cut.range, (i, j) => if j <= i: prev[j] + cost(j..i)).map(.val) ``` (`if` without `else` is `None` when false: the expression form of a partial function.) ## Small patterns that recur | Form | Meaning | Cost | |---|---|---| | `a.lis(strict: true)` | positions of one longest increasing subsequence, `List` | O(n log n) | | `a.prev_smaller()`, `a.next_smaller()` | `[D]?D` nearest smaller to each side (monotone stack); larger with `by: desc` | O(n) | | `Window(enter, leave)`, `w.move(to: r)` | stateful sliding piece (two pointers, Mo, D&C costs) | O(distance moved) | | `MonoDeque(min)`, `WindowFold(op)` | sliding min / fold of any monoid | O(1) amortized | | `backtrack(start, next)` | `yields Step`; `step.prune()`, `break`, `return` | per node | ## Open 1. **`V.ranges` and `r.splits`.** A domain of pieces makes interval DP a table like any other. Alternative: `[V, V.cuts]Int` with `l <= r` checked by hand (C++'s way, half the table unused). 2. **`if` without `else` as `?T`.** Makes partial cost functions one line. Alternative: write `if c: x else: None`. --- # Round 7: sequence patterns URL: /docs/ref/lib/sequence-patterns Normative text from [spec/lib/sequence-patterns.md](https://github.com/ryanbai1412/cp-lang/blob/main/spec/lib/sequence-patterns.md). Status: proposal for review. Scope: the everyday sequence problems (runs, windows, two pointers, nearest smaller, contribution counting, prefix tricks, adjacent pairs, circular arrays, grouping) and how a few general mechanisms cover all of them. Builds on round 2 (views keep keys, folds, scans) and round 5 (op values, laws, `Window(op)`). ## The model in one paragraph **Every pattern is a way to cut a sequence into pieces, plus a fold over each piece.** Pieces are views that keep the source's positions (round 2), so an answer is always a position or a range of the input, never an offset you translate back. How the pieces are cut is one of five shapes: fixed length (`windows`, `chunks`), equal or linked neighbours (`runs`), separators (`split`), the longest or shortest piece satisfying a condition at each end (`maximal`, `minimal`), and the piece where an element wins (`spans`). How each piece is summarized is an op value from round 5, and the op's laws pick the O(1)-per-step strategy, so "sliding min", "sliding sum" and "sliding gcd" are one call with different ops. State that isn't a fold (distinct counts, a frequency table) implements one small protocol, `Track`, which two pointers and Mo's algorithm both accept. ## 1. Mechanisms | # | Mechanism | Forms | Where it comes from | |---|---|---|---| | 1 | pieces are views with keys | `w.keys`, `w.len`, `a[w]` | round 2 | | 2 | cutting into pieces | `windows`, `chunks`, `runs`, `split`, `maximal`, `minimal`, `spans` | this doc | | 3 | folding a piece | `w.fold(op)`, `w.sum()`, `w.max(by:)`; `pieces.fold(op)` as a sliding fold | round 5 | | 4 | prefix folds over cuts | `a.scan(op)`, `pre[r]` | round 2 | | 5 | state that grows and shrinks | `Track`: `push(x)`, `pop(x)` | this doc | | 6 | nearest neighbour by order | `prev_smaller`, `next_smaller`, `prev_same`, `next_same` | this doc | Everything else is an idiom over these six, shown in section 3. ## 2. The pieces All of these are O(1) to make and lazy, read without parentheses only when they are views (`a.adjacent`), and yield views of `a` keyed by `a`'s positions. Each works on any `Indexed` (`[D]T`, `List`, `Str`, a slice). | Form | Pieces | Cost to walk | |---|---|---| | `a.windows(k)` | every length-`k` piece, left to right; none if `k > a.len` | O(n) | | `a.chunks(k)` | consecutive length-`k` pieces; the last may be shorter | O(n) | | `a.runs(by: key)` | maximal pieces of equal `key` | O(n) | | `a.runs(link: (x, y) => Bool)` | maximal pieces where every adjacent pair links | O(n) | | `a.split(sep: p)` | pieces between elements where `p` holds (separators excluded; empty pieces kept) | O(n) | | `a.maximal(state, ok:)` | for each right end, the longest piece ending there that is `ok` | O(n) amortized | | `a.minimal(state, ok:)` | for each right end, the shortest piece ending there that is `ok`, or none | O(n) amortized | | `a.maximal(state, ok:, anchor: Anchor.Start)` | the same keyed by left end: the longest piece starting at each position | O(n) amortized | | `a.spans(by: key)` | for each position, the widest piece where it is the minimum | O(n) | ```cp s.runs() // "aabccc" -> "aa", "b", "ccc" a.runs(link: (x, y) => x < y) // strictly increasing runs a.runs(link: (x, y) => y - x <= d) // gaps of at most d line.split(sep: c => c == ' ') // words, as pieces of line ``` `runs(by:)` is `runs(link: (x, y) => key(x) == key(y))`; it stays as its own option because equal-key runs are the common case and need no lambda. ### Folding pieces: the sliding fold A sequence of pieces has `.fold(op)`, which yields one value per piece. On `windows(k)` it is the sliding fold, O(1) amortized per window, with the strategy chosen by the op's laws exactly as `Window(op)` chooses it: | Law of `op` | Strategy | Cost per step | |---|---|---| | `Group` (`+`, `^`, `Mod` `*` without zero) | add the new element, subtract the old | O(1) worst case | | `Selective` (`min`, `max`, `min(by:)`) | monotone deque | O(1) amortized | | any `Op` (`gcd`, matrix product, `MaxSub`) | two stacks | O(1) amortized | ```cp a.windows(k).fold(+).max()! // best sum of k consecutive a.windows(k).fold(min) // sliding minimum, one per window a.windows(k).fold(gcd).count(g => g > 1) ``` On other pieces (`runs`, `chunks`, `split`) `.fold(op)` folds each piece directly, which is already O(n) total since they don't overlap. Writing `for w in a.windows(k): w.sum()` is O(nk); the lint `window_refold` suggests `.fold(+)`. This replaces `sliding_min`, `sliding_max`, `sliding_fold`, `MonoDeque` used for fixed windows, and the hand-written two-stack queue. ### Two pointers: `maximal` and `minimal` Two pointers is a search for, at each right end, the extreme left end where a condition holds. It needs one fact about the condition: - `maximal` needs `ok` **hereditary**: if a piece is ok, every piece inside it is ok (sum at most K over non-negative values, at most k distinct). - `minimal` needs `ok` **upward closed**: if a piece is ok, every piece containing it is ok (sum at least S, contains every colour). Both walk `r` left to right, move `l` only forward, and keep `state` in step by calling `state.push(a[r])` and `state.pop(a[l])`. They return one piece per right end, `[D]Slice` (`minimal`: `[D]?Slice`). ```cp pub trait Track: fn push(mut self, x: T) // x joins at the right end fn pop(mut self, x: T) // x leaves at the left end (the oldest) pub enum Anchor = Start | End pub fn maximal>(self: [D]T, mut state: S, ok: S -> Bool, anchor: Anchor = Anchor.End) -> [D]Slice<[D]T> ``` `Track` implementations that already exist: | Type | `push` / `pop` | Typical `ok` | |---|---|---| | `Window(op)` | fold queue | `w.all <= k` | | `Counter` | count up / down; `.len` is the distinct count | `c.len <= k` | | `Bag` (sorted multiset) | insert / erase one | `b.max! - b.min! <= d` | | `track(s, add:, remove:)` (a `Tracked`) over any structure `s` | your two closures on `mut s` | a predicate on `t.state` | | `undoing(s, add:)` (an `Undoing`) over any `Undo` (`mark`/`undo_to`: rollback `Dsu`, `ParityDsu`, `RollbackArray`) | apply / queue-undo: each element re-applied O(log n) times amortized | `u => not u.state.consistent` | ```cp let longest = a.maximal(Window(+), ok: w => w.all <= K).max(by: .len)! let atmost_k = a.maximal(Counter(0), ok: c => c.len <= k) let count = atmost_k.map(.len).sum() // subarrays with <= k distinct let shortest = a.minimal(Window(+), ok: w => w.all >= S).present().min(by: .len) ``` - **The promise is checked where it is cheap.** Hereditary and upward closed are promises like round 5's laws. `cpl stress` compares `maximal`/`minimal` against their O(n²) definition on small inputs, so a non-monotone `ok` shows up as a counterexample naming the piece. - **Mo's algorithm takes the same protocol.** `mo(queries, state, answer:)` with `state: Track` replaces `add:`/`remove:` closures; Mo pushes and pops at both ends, so it needs a state whose answer ignores order (`Counter`, `Bag`), and `Window(op)` there needs `Commutative`. `track(s, add:, remove:)` keeps the closure form one call away. - **Results are keyed by the right end.** `maximal` and `minimal` return `[D]Slice` (`[D]?Slice`), like the ring forms, so "the group ending at `i`" is `g[i]` and the starts are `g.map(p => p.first!)`. With `anchor: Anchor.Start` the same pass keys each piece by its left end, so "the longest group starting at `s`" is `g[s]`: the next pointer for greedy jumping, `Lift.of(s => g[s].last!.next)` (Osumnjičeni). - **The moving window over positions** (`Window(enter, leave)` today, for divide-and-conquer DP costs) becomes `Sweep(state)` with `s.move(to: r)`, again over a `Track`. This frees the name `Window` for round 5's fold queue. ### Contribution counting: `spans` "Sum of minimums over all subarrays", "largest rectangle in a histogram" and "count subarrays where `a[i]` is the maximum" all need, for each `i`, the widest piece in which `a[i]` is the minimum. `a.spans(by: key)` gives it as `[D]Range`, ties broken so every subarray is counted once (strict on the left, non-strict on the right). Maximum is `by: desc`. ```cp let sp = a.spans() let total = a.keys.map(i => a[i] * (sp[i].l..i.r).len * (i.l..sp[i].r).len).sum() let rect = a.keys.map(i => a[i] * sp[i].len).max()! // histogram ``` This replaces `max_histogram` and covers the contribution technique with one structure; `cartesian_tree` stays, since it is a tree. ### Nearest by order | Form | Result | |---|---| | `a.prev_smaller(by:, strict: true)` | `[D]?D`: nearest earlier position with a smaller key | | `a.next_smaller(by:, strict: true)` | `[D]?D`: nearest later one | | `a.prev_same(by:)`, `a.next_same(by:)` | `[D]?D`: nearest earlier/later position with an equal key | Larger is `by: desc` (round 5's one way to flip an order), so `prev_less`, `prev_greater`, `next_less`, `next_greater` merge into two names. `prev_same` is the "last occurrence" array behind distinct-count queries. `MonoStack` stays for custom stacks (rollback on trees). ## 3. Idioms over the mechanisms No helper is added for these; each is one or two lines. | Problem | Code | |---|---| | run-length encoding | `[(r.first!, r.len) for r in s.runs()]` | | longest run | `s.runs().max(by: .len)!.len` | | adjacent differences | `a.adjacent.map((x, y) => y - x)` | | count adjacent pairs with a property | `a.adjacent.count((x, y) => x > y)` | | every pair `i < j` (brute force) | `a.pairs()`, O(n²) to walk | | best subarray sum (Kadane) | `a.fold(MaxSub)` (round 5's summary; the same op answers range queries in a `SegTree`) | | maximum and how often | `a.fold(MaxCount)` | | prefix records | `a.keys.filter(i => a[i] > pre[i.l])` with `pre = a.scan(max)` | | count subarrays with sum `K` | `var seen = Counter(0)`; `for c in pre.keys: ans += seen[pre[c] - K]; seen.push(pre[c])` | | range sums | `pre = a.scan(+)`; `pre[r.r] - pre[r.l]` | | first position where a prefix fold passes `x` | `pre.keys.first_true(c => pre[c] >= x)` (monotone) or `.first(...)` | | polygon edges | `poly.cyclic_pairs` | | circular windows | `a.ring.windows(k)` (below) | | group equal keys anywhere | `a.group(by: k)`, `a.tally(by: k)`, `a.map(k).buckets()` (domain-keyed) | | value held by more than half, from equality alone | `a.majority(eq: same)` | | ranges strictly below both neighbours outside them | `a.valleys()` | | dedup | `a.dedup()` (adjacent), `a.distinct(by:)` (anywhere) | | merge sorted sequences | `merge(a, b, by:)` yields in order; `kway_merge(lists, by:)` | | inversions, LIS | `a.inversions()`, `a.lis(strict:)` | ### Circular sequences: `a.ring` `a.ring` is a view of `a` read as a cycle: `a.ring.windows(k)` yields the `n` windows starting at each position (wrapping), `a.ring.from(i)` walks all `n` positions starting at `i`, and every element is still a position of `a`. It replaces the "double the array" trick, which costs O(n) memory and loses the positions. A wrapping window isn't one range of `a`, so its `.keys` is a sequence of positions, not a `Range`: wrapping pieces are `RingSlice`s with `start`, `end`, `len` and `keys`. `a.ring.next(i)` and `a.ring.prev(i)` step with wrap-around. The positions alone, with no array, are a `RingRange`: `a.ring.span(i, k)` is the `k` positions from `i` on, `slice.range` takes them from a `RingSlice`, and `pre.cyclic_sum(r)` sums a `Prefix` over one in O(1). Two pointers wrap too. `a.ring.maximal(state, ok:)` and `a.ring.minimal(state, ok:)` return `[D]RingSlice` and `[D]?RingSlice`: for each position as the last element, the longest or shortest wrapping piece (at most n elements) ending there that is `ok`. They walk two laps, so they cost O(n) pushes and pops. Problems about "everything except `l..=r`" become a ring window from `r` round to `l`: ```cp // BOI 2020 Joker: do the streets outside l..=r still hold an odd cycle? let dsu = undoing(ParityDsu(), add: (mut d, e) => d.unite(e.0, e.1)) let odd = street.ring.minimal(dsu, ok: u => not u.state.consistent) for (l, r) in read<[q](Street, Street)>(): let open = m - (l..=r).len print(yes(odd[street.ring.prev(l)].map(w => w.len <= open) ?? false)) ``` `undoing` is the queue-undo trick as a `Track`: a structure that can only undo its newest change (a rollback DSU) still serves a window that drops from the front. ## 4. How the parts stay coherent - **Same answer type everywhere.** Pieces are views keyed by the input's positions; per-position results are `[D]...`; per-piece results are a `Seq` you fold, collect or `max(by:)`. - **Same ops everywhere.** `+`, `min`, `gcd`, `MaxSub`, `min(by:)` mean the same thing in `w.fold`, `windows(k).fold`, `Window`, `SegTree`, `scan` and `Lift`; the laws pick each structure's strategy. - **Same order vocabulary.** Every "smaller" is `by:` with `desc` for larger, as in `sort`, `Heap` and `min`. - **Same state protocol.** `Track` is accepted by `maximal`, `minimal`, `Sweep` and `mo`; `Window`, `Counter` and `Bag` implement it, and so can a user struct. - **Costs read off the code.** Making a piece sequence is O(1); walking it is O(n) total for non-overlapping pieces, `windows(k).fold` is O(n), and re-folding each window is linted. ## 5. What goes away | Today | Becomes | |---|---| | `sliding_min`, `sliding_max`, `sliding_fold` | `a.windows(k).fold(op)` | | `MonoDeque`, `WindowFold`, `DequeFold` | `Window(op)` (round 5) | | `Window(enter, leave)` | `Sweep(state)` over a `Track` | | `prev_less`, `prev_greater`, `next_less`, `next_greater` | `prev_smaller`/`next_smaller` with `by:` | | `max_histogram` | `a.spans()` plus a fold | | `max_subarray`, `max_count`, `reduce` | `a.fold(MaxSub)`, `a.fold(MaxCount)`, `a.fold(op)` | | `diffs`, `adjacent_diff`, `with_next` | `a.adjacent.map(...)`, `Diff` (round 5), `a.with_prev` | | `record_highs` | `a.scan(max)` and a filter | | `chunk_by`, `run_ranges` (already gone) | `runs` | | `mo(add:, remove:)` | `mo(queries, state, answer:)`; `track(s, add:, remove:)` | ## Open 1. **`spans` tie-breaking.** Strict-left, non-strict-right counts each subarray once; a `ties:` option could expose the other three choices, but no dream needs them yet. 2. **`a.ring` keys.** A wrapping window's keys are a position sequence, not a range. The alternative is to forbid `ring.windows` and require `a.ring.from(i).take(k)`. --- # std.strings: complete design URL: /docs/ref/lib/strings Normative text from [spec/lib/strings.md](https://github.com/ryanbai1412/cp-lang/blob/main/spec/lib/strings.md). > **0.3.0 status.** This chapter is the family's design survey and API. > Where it disagrees with the core chapters or the aligned rounds, they > win: `core/03-numbers-layout.md` (four number types, no `I32`/`U32`, > `Mod

` not `Mint`), `core/05-ownership.md` (constructors own their > results), `core/07-sequences.md` (capabilities, views keep keys), > `lib/ops-ranges.md` (`Op`/`Monoid`/laws, `each(...)`, no > `RangeFenwick`, `MinHeap`/`MaxHeap` as `Heap(by:)`) and > `lib/sequence-patterns.md`. The stubs in `std/` are the signatures of > record. Reconciliation of this text is tracked in `delta/`. This document designs the `std.strings` area of the CP Lang standard library top down: the contest patterns it must cover, one coherent API with costs and laws, how it uses domains and index spaces, what stays user code, and five real contest problems written against it. Facts checked directly in this repository (`stdlib/strings.cp`, `examples/local-lib/str/`, `proto/ports/ecnerwala/ucup5s05f_orig.cpp`, `proto/ports/scout_batch_10/`, `research/friction-backlog-batch-10.md`) are verified; external library inventories (KACTL, AtCoder Library, CP-Algorithms) are standard public references. ## 1. Survey of contest patterns String problems across Codeforces Div. 1, AtCoder Grand/WTF, ICPC World Finals, and IOI cluster into six families. **Pattern matching, borders, and periodicity.** Single-pattern search, prefix function (KMP), Z-function, enumerating all borders of a string, shortest period, longest suffix-prefix overlap between two strings, and matching lengths of a pattern across a text without inventing a sentinel outside the alphabet. KACTL ships `KMP` (`pi`, `match`) and `Zfunc`; AtCoder Library ships `z_algorithm`. In our corpus, `ctsc06p1` sums `m^b` over all borders, `noip20p2` uses `z_function` to count `(AB)^k C` splits, and `btoi19p5` wants the longest prefix of a pattern ending at each text position (`T5` in `research/friction-backlog-batch-10.md`). **Lyndon words and cyclic rotations.** Lexicographically smallest cyclic shift and Duval's Lyndon factorization. KACTL ships `MinRotation` (Booth/Duval, O(n)); CP-Algorithms pairs it with `lyndon_factorization` (Duval, O(n)), from which `min_rotation` is five lines. Both are short, notorious for off-by-one bugs under contest pressure, and work on any `Ord` sequence. **Polynomial rolling hashing.** O(1) substring equality, concatenation of hashes, O(log n) LCP/LCS via binary search, lexicographic substring comparison, and 2D grid rectangle hashing. KACTL ships `Hashing` (arithmetic mod `2^64 - 1` with fixed or randomized base) and `Hashing-codeforces` (double modulus against anti-hash hacks). Six of ten submissions in `scout_batch_10` hand-rolled their own hasher (`noi16p1`, `noi17p2`, `year2018p7`, `noip20p2`, `btoi19p5`, `nccc10s3`). `stdlib/strings.cp` already provides `HashVal` and `RollingHash` (double-mod `10^9 + 7` and `10^9 + 9`, random per-instance bases, composable into 2D via `HashVal.hash_token`), and `examples/local-lib/str/hash2d.cp` provides `Hash2D`. What is missing from `RollingHash` is `lcp`, `lcs`, and `lcp_with` (`noi16p1`), plus promoting `Hash2D` with double-mod `HashVal` so single-mod collisions are impossible on Codeforces. **Suffix structures.** Suffix array (SA-IS, O(n) for bounded alphabets and O(n log n) for general `Ord`), Kasai LCP array (O(n)), O(1) arbitrary-pair LCP queries via RMQ, pattern range search in O(|pat| log n), O(1) substring comparison, and the suffix automaton (SAM, online O(n) amortized) for distinct substrings, endpos counts, and longest common substring. AtCoder Library ships `suffix_array` (SA-IS) and `lcp_array` (Kasai). KACTL ships `SuffixArray` and `SuffixTree`. In `proto/ports/ecnerwala/ucup5s05f_orig.cpp`, ecnerwala's `src/seq/suffix_array.hpp` layers `SuffixArrayBase` (`sa`, `rank`), `SuffixArrayLCPBase` (`lcp`), `SuffixArrayRMQBase` (`get_lcp(a, b)`, `get_split(l, r)`), and `PrefixArrayRMQ` (`get_lcs(a, b)`). In our corpus, `saspeed` tests O(n) SA-IS speed at `n = 10^6`, `noi15p5` joins adjacent suffixes by decreasing LCP, `nccc10s3` binary-searches the suffix array for pattern occurrences (`T4`), and `ucup5s05f` walks the suffix tree over `sa` and `lcp`. `examples/local-lib/str/suffix_automaton.cp` already has a clean `SuffixAutomaton`, though its `occurrences()` uses O(n log n) sort instead of O(n) counting sort. **Palindromes.** Manacher's algorithm for all odd/even palindrome radii in O(n), O(1) substring palindrome queries, total palindrome count, longest palindromic substring, and the palindromic tree (Eertree) for distinct palindromes, per-palindrome occurrence counts, and O(n log n) palindrome partition DP via series links. KACTL ships `Manacher`; `examples/local-lib/str/ palindromes.cp` has Manacher's radii. `plan/STDLIB.md` already schedules `manacher` and `is_palindrome`. **Tries and multi-pattern matching.** Static/dynamic prefix tries over an alphabet domain (`Trie`) for dictionary lookup, prefix counting, and binary XOR maximization (`ioi08p1`, `sac22cc3p5`), and Aho-Corasick (`AhoCorasick`) for simultaneous multi-pattern matching, occurrence counting, and DP over strings avoiding or containing forbidden words. KACTL ships `AhoCorasick`; `examples/local-lib/str/trie.cp` and `examples/local-lib/str/aho_corasick.cp` already demonstrate the alphabet-domain pattern. ## 2. Design principles and index spaces **Flat 0-based positions over any `Indexed` / `Seq` sequence.** Per decision 1.6, `Str` is a flat `0..len`-indexed sequence of 1-byte ASCII `Char` values. All sequence-level algorithms (`z_function`, `prefix_function`, `find_all`, `common_prefix_len`, `common_suffix_len`, `period`, `borders`, `prefix_matches`, `overlap`, `lyndon_factorization`, `min_rotation`, `lyndon_runs`, `is_palindrome`, `manacher`, `suffix_array`, `SuffixArray`) are generic over `Indexed` (`Str`, `StrView`, `List`, `ListView`, and `[D]T` domain arrays) and return 0-based `Int` positions and lengths; all alphabet-domain automata (`SuffixAutomaton`, `PalindromicTree`, `Trie`, `AhoCorasick`) accept any `Seq` of alphabet elements. **Alphabet domains on automata.** `Trie`, `AhoCorasick`, `SuffixAutomaton`, and `PalindromicTree` take an alphabet domain `A` (such as `domain Letter = 'a'..='z'`, `domain Bit = 0..2`, or `domain Digit = '0'..='9'`). Every state stores its transitions as `[A]?Int` or `[A]Int`. This beats hardcoding 26 lowercase letters on every axis: binary alphabets use 2 slots instead of 26, uppercase/digit/general alphabets work without `c - 'a'` arithmetic, and invalid characters are caught when entering the domain. **Domain-aware hashing.** `RollingHash` accepts `Str`, `List`, `[D]T`, or `[D]HashVal`, and `.get(r)` accepts `Range` or `Range`. `Hash2D` is parameterized by the grid's row and column domains `R` and `C`, taking `Range` and `Range` in `.rect(rows, cols)`, so row/column swaps are type errors. **Layered cost for suffix arrays.** Computing only `sa` and `lcp` is O(n) via `suffix_array(s).sa` and `.lcp`. When a solution also wants `rank`, O(1) `lcp_between(i, j)`, O(|pat| log n) `rank_range(pat)`, O(log n) `lcp_range(i, len)`, or O(1) `compare`, it constructs `SuffixArray(s)` at documented O(n log n) build cost. Nothing is built secretly behind `suffix_array(s)`. **Zero-cost safety and guessable names.** Every algorithm uses its textbook name (`z_function`, `prefix_function`, `manacher`, `suffix_array`, `lyndon_factorization`, `min_rotation`, `AhoCorasick`, `SuffixAutomaton`, `PalindromicTree`, `Trie`, `RollingHash`, `Hash2D`). Options are named arguments (`bases:`). Container-like structures follow `plan/STDLIB.md` §2 (`len`, `root`, `step`, `find`, `contains`, `add`, `remove`, `count`). ## 3. Coherent API, costs, and laws ### 3.1 `Str` and `Char` helpers ```cp fn repeat(self: Str, n: Int) -> Str // O(n * self.len) fn starts_with(self: Str, p: Str, at: Int = 0) -> Bool // O(p.len) fn ends_with(self: Str, p: Str) -> Bool // O(p.len) fn search

(self: Str, p: P) -> ?Int // O(self.len + p.len) fn rsearch

(self: Str, p: P) -> ?Int // O(self.len + p.len) fn count(self: Str, c: Char) -> Int // O(self.len) @get fn lower(self: Char) -> Char // O(1) @get fn upper(self: Char) -> Char // O(1) @get fn digit(self: Char) -> Int // O(1); traps outside '0'..'9' fn is_palindrome(s: S) -> Bool // O(n) fn common_prefix_len(self: A, other: B) -> Int // O(min) fn common_suffix_len(self: A, other: B) -> Int // O(min) ``` Laws: - `s.repeat(0) == ""` and `s.repeat(a + b) == s.repeat(a) + s.repeat(b)`. - `s.search(p) == Some(i)` implies `i` is the minimum index with `s[i..i + p.len] == p`. - `is_palindrome(s)` iff `s[i] == s[n - 1 - i]` for all `0 <= i < n`. ### 3.2 Pattern matching, borders, periods, and Lyndon words ```cp fn z_function(s: S) -> List // O(n) fn prefix_function(s: S) -> List // O(n) fn find_all(self: S, pat: P) -> yields Int // O(|self| + |pat|) fn period(s: S) -> Int // O(n) fn borders(s: S) -> yields Int // O(n); longest first fn prefix_matches(self: S, pat: P) -> List // O(|self| + |pat|); entry i is the longest prefix of pat ending at self[i] fn overlap(a: A, b: B) -> Int // O(|a| + |b|); longest suffix of a that is a prefix of b fn lyndon_factorization(s: S) -> List // O(n) Duval; start indices of the unique non-increasing Lyndon factors fn min_rotation(s: S) -> ?K // start key; None on empty // O(n) Duval/Booth; start index of the lexicographically least cyclic shift fn lyndon_runs(s: S) -> List<(l: Int, r: Int, period: Int)> // O(n log n) Bannai runs theorem; all maximal periodic repetitions ``` Laws: - `z_function(s)[i] == lcp(s, s[i..])` for every `i in 0..n`. - `prefix_function(s)[i]` is the maximum `k <= i` with `s[..k] == s[i + 1 - k..=i]`. - `borders(s)` yields every `k in 1..n` with `s[..k] == s[n - k..]`, strictly decreasing. - `period(s)` is `0` when `s.is_empty`, else the minimum `d in 1..=n` with `s[i] == s[i + d]` for all `0 <= i < n - d`. - `prefix_matches(text, pat)[i]` is the maximum `k <= min(i + 1, pat.len)` with `pat[..k] == text[i + 1 - k..=i]`, and `i + 1 - pat.len` is yielded by `find_all(text, pat)` iff `prefix_matches(text, pat)[i] == pat.len`. - `overlap(a, b)` is the maximum `k <= min(a.len, b.len)` with `a[a.len - k..] == b[..k]`. - For `starts = lyndon_factorization(s)`, every factor `w_j` is strictly smaller than all its proper non-empty suffixes, and `w_0 >= w_1 >= ...`. - `min_rotation(s)` achieves the minimum cyclic shift `s[r..] + s[..r]` over all `r in 0..n` (and `0` when `n == 0`). ### 3.3 Palindromes ```cp struct Palindromes(odd: List, even: List): fn is_palindrome(self, r: R) -> Bool // O(1); Range or Range fn count(self) -> Int // O(n); total palindromic substrings fn longest(self) -> (l: Int, r: Int) // O(n); longest palindromic range fn manacher(s: S) -> Palindromes // O(n) struct PalindromicTree: fn new() -> PalindromicTree // O(|A|) fn of(s: S) -> PalindromicTree // O(n * |A|) mem, O(n) time fn push(mut self, a: A) -> Int // O(1) amortized; returns last state @get fn len(self) -> Int // O(1); states incl. 2 roots @get fn distinct(self) -> Int // O(1); len - 2 fn pal_len(self, state: Int) -> Int // O(1) fn link(self, state: Int) -> Int // O(1); longest proper pal suffix fn step(self, state: Int, a: A) -> ?Int // O(1); a + P + a fn diff(self, state: Int) -> Int // O(1); pal_len - pal_len(link) fn series_link(self, state: Int) -> Int // O(1); nearest ancestor with other diff fn occ_counts(self) -> List // O(n); total occurrences per state ``` Laws: - For `p = manacher(s)`: `p.odd[i]` is the maximum `k` with `s[i - k + 1..i + k]` palindromic; `p.even[i]` is the maximum `k` with `s[i - k..i + k]` palindromic. - `p.is_palindrome(l..r) == is_palindrome(s[l..r])` for all `0 <= l <= r <= n`. - `p.count == sum(p.odd) + sum(p.even)`, and equals `sum(pt.occ_counts()[2..])` on `pt = PalindromicTree.of(s)`. - `pt.distinct` equals the number of distinct non-empty palindromic substrings of `s`, and `pt.distinct <= n`. - Walking `state = pt.series_link(state)` from any state to root 0 takes at most `O(log n)` steps. ### 3.4 Rolling hashing ```cp struct HashVal(h1: Int, h2: Int): @get fn hash_token(self) -> Int // O(1) trait Hashable: @get fn hash_token(self) -> Int = Int(self) struct RollingHash: fn new(seq: S, bases: ?(Int, Int) = None) -> RollingHash // O(n) fn with_bases(seq: S, bases: (Int, Int)) -> RollingHash // O(n) @get fn len(self) -> Int // O(1) @get fn all(self) -> HashVal // O(1) fn slice(self, l: Int, r: Int) -> HashVal // O(1) fn get(self, r: R) -> HashVal // O(1) fn combine(self, a: HashVal, b: HashVal, b_len: Int) -> HashVal // O(1) fn lcp(self, a: Int, b: Int) -> Int // O(log n) fn lcs(self, a: Int, b: Int) -> Int // O(log n) fn lcp_with(self, a: Int, other: RollingHash, b: Int) -> Int // O(log n) struct Hash2D: fn new(code: (R, C) -> Int, bases: ?(Int, Int) = None) -> Hash2D // O(R * C) fn rect(self, rows: Range, cols: Range) -> HashVal // O(1) ``` Laws: - Equal slices always produce equal `HashVal`s; distinct slices collide with probability at most `len / (10^9 + 7) * len / (10^9 + 9) < 10^-18 * len^2`. - `h.combine(h.slice(l, m), h.slice(m, r), r - m) == h.slice(l, r)` for all `0 <= l <= m <= r <= h.len`. - `h.lcp(a, b)` equals the exact LCP of `s[a..]` and `s[b..]` whp; `h.lcs(a, b)` equals the exact LCS of `s[..a]` and `s[..b]` whp. - `Hash2D.rect` returns equal `HashVal`s for identical sub-rectangles of the same shape; sharing `bases:` makes rectangles comparable across two grids. ### 3.5 Suffix structures ```cp fn suffix_array(s: S) -> SuffixArray // the `SuffixArray` below; `.sa`, `.lcp` (Kasai) struct SuffixArray: s: List sa: List rank: List lcp: List fn new(s: S) -> SuffixArray // O(n log n) build (SA-IS + Kasai + RMQ) @get fn len(self) -> Int // O(1) fn lcp_between(self, i: Int, j: Int) -> Int // O(1) fn rank_range(self, pat: P) -> Range // O(|pat| log n); rank range lo..hi fn count(self, pat: P) -> Int // O(|pat| log n) fn lcp_range(self, i: Int, len: Int) -> Range // O(log n); rank range whose LCP with suffix i is >= len fn compare(self, l1: Int, r1: Int, l2: Int, r2: Int) -> Int // O(1); -1, 0, or 1 comparing s[l1..r1] vs s[l2..r2] @get fn distinct(self) -> Int // O(n); distinct non-empty substrings struct SuffixAutomaton: fn new() -> SuffixAutomaton // O(|A|) fn of(s: S) -> SuffixAutomaton // O(n * |A|) mem, O(n) time fn push(mut self, a: A) // O(1) amortized @get fn root(self) -> Int // O(1); 0 @get fn len(self) -> Int // O(1); <= max(2n - 1, 1) fn step(self, state: Int, a: A) -> ?Int // O(1) fn link(self, state: Int) -> ?Int // O(1) fn longest(self, state: Int) -> Int // O(1) fn shortest(self, state: Int) -> Int // O(1) fn first_pos(self, state: Int) -> Int // O(1); end index of first occurrence fn find(self, word: S) -> ?Int // O(|word|) fn contains(self, word: S) -> Bool // O(|word|) @get fn distinct(self) -> Int // O(states) fn topo_order(self) -> List // O(states); non-decreasing longest fn occ_counts(self) -> List // O(states); endpos count per state ``` Laws: - `sa` is a permutation of `0..n` sorting suffixes strictly ascending; `rank[sa[j]] == j`. - `lcp[j] == lcp_between(sa[j], sa[j + 1])` for all `0 <= j < n - 1`. - `lcp_between(i, i) == n - i` and `lcp_between(i, j) == lcp_between(j, i)`. - `sa[j]` starts with `pat` iff `j in sa_obj.rank_range(pat)`. - `sa_obj.distinct == sam.distinct` for any string `s`. - `sam.contains(w)` iff `sa_obj.count(w) > 0`; when `sam.find(w) == Some(v)`, `sam.occ_counts()[v] == sa_obj.count(w)`. ### 3.6 Tries and Aho-Corasick ```cp struct Trie: fn new() -> Trie // O(|A|) @get fn root(self) -> Int // O(1); 0 @get fn len(self) -> Int // O(1); nodes incl. root fn step(self, node: Int, a: A) -> ?Int // O(1) fn find(self, word: S) -> ?Int // O(|word|) fn add(mut self, word: S) -> Int // O(|word|); returns terminal node fn remove(mut self, word: S) -> Bool // O(|word|) fn count(self, word: S) -> Int // O(|word|) fn count_prefix(self, prefix: S) -> Int // O(|prefix|) fn ends_at(self, node: Int) -> Int // O(1) fn pass_at(self, node: Int) -> Int // O(1) struct AhoCorasick: fn new(patterns: List) -> AhoCorasick // O(sum |p| * |A|) @get fn root(self) -> Int // O(1); 0 @get fn len(self) -> Int // O(1); states incl. root fn step(self, state: Int, a: A) -> Int // O(1); total DFA transition fn link(self, state: Int) -> Int // O(1); failure link fn hit(self, state: Int) -> Bool // O(1); any pattern ends here fn words_at(self, state: Int) -> List // O(output); longest first fn find_all(self, text: S) -> yields (at: Int, pattern: Int) // O(|text| + output); ordered by end position fn counts(self, text: S) -> List // O(|text| + states) ``` Laws: - On `Trie`, `add` increments `count(w)` and `count_prefix(p)` for every prefix `p` of `w` by 1; `remove` reverses `add` when `count(w) > 0` and is a no-op returning `false` otherwise. - On `AhoCorasick`, `find_all(text)` yields `(at, p)` iff `text[at..at + patterns[p].len] == patterns[p]`, and `counts(text)[p]` equals the number of yielded pairs with `pattern == p`. ## 4. What stays user code - **Mergeable, persistent, and custom-aggregate tries** (such as `cf2261g`'s suffix-AND binary trie merging): every problem attaches different node fields and merge semantics; a 15-line `struct Node` + `List` arena is clearer and faster than a bloated generic hook. - **Explicit suffix trees** (such as `ucup5s05f`'s suffix-tree edge power sums): `suffix_array(s).lcp` with a 15-line monotonic stack, or the suffix-link tree of `SuffixAutomaton`, already gives the suffix tree without locking in an edge-label representation. - **Automaton DP** (avoiding-words DP over `AhoCorasick`, palindrome factorization DP over `PalindromicTree`, LCS over `SuffixAutomaton`): the automata expose `root`, `len`, `step`, `link`, `hit`, `diff`, `series_link`, and `topo_order`, so the DP recurrence itself is 8–15 lines of transparent user code. - **Unicode, regex, and locale**: out of scope for competitive programming (`Str` is 1-byte ASCII). ## 5. Five real problems written against the API ### 5.1 CTSC 2006 — Singing Kingdom (`ctsc06p1`) Expected number of random draws from `1..=m` until `name` appears as a contiguous block, mod `10^4` (four digits). By the martingale argument, the expected wait is the sum of `m^b` over every border `b` of `name`, including `name` itself. ```cp // Expected wait for a word over 1..=m is sum(m^b) over every border b // (the whole word plus every proper non-empty border). use std.strings.{borders} type Z = Mod<10_000> let (m, t): (Int, Int) = read() repeat t: let n: Int = read() let name: [0..n]Int = read() var wait = Z(m) ** n for b in borders([name[i] for i in 0..n]): wait += Z(m) ** b print(f"{wait.v:04}") ``` ### 5.2 NOI 2015 — Wine Tasting (`noi15p5`) For every `r in 0..n`, count pairs of suffixes sharing at least `r` letters and find the maximum product of their scores. Sort suffixes, then merge adjacent ranks from largest LCP down using `DsuOf`. ```cp // Two suffixes are r-alike iff every adjacent LCP between their ranks is >= r. // Sweep r downward, merging adjacent ranks and tracking each group's min/max score. use std.strings.{SuffixArray} use std.dsu.{DsuOf} struct Span(lo: Int, hi: Int) let n: 1..=300_000 = read() let s: Str = read() let score: [0..n]Int = read() let sa = SuffixArray(s) domain Rank = 0..n var groups = DsuOf( r => Span(score[sa.sa[r.to_idx]], score[sa.sa[r.to_idx]]), (a, b) => Span(min(a.lo, b.lo), max(a.hi, b.hi)), ) var (pairs, best): (Int, ?Int) = (0, None) let order = sorted(0..n - 1, by: j => -sa.lcp[j]) var at = 0 var ans: List<(Int, Int)> = [] for r in (0..n).rev: while at < order.len and sa.lcp[order[at]] >= r: let j = order[at] at += 1 let (u, v) = (Rank(j), Rank(j + 1)) let (su, sv) = (groups.get(u), groups.get(v)) pairs += groups.size(u) * groups.size(v) best max= max(su.lo * sv.lo, su.lo * sv.hi, su.hi * sv.lo, su.hi * sv.hi) groups.unite(u, v) ans.push((pairs, best ?? 0)) for (cnt, prod) in ans.rev: print(cnt, prod) ``` ### 5.3 NOI 2016 — Excellent Splits (`noi16p1`) Count substrings of the form `AABB` (`A`, `B` non-empty). For each half-length `w`, every square `AA` covers a unique checkpoint pair `(q, q + w)` with `q` a multiple of `w`; its valid start range is determined by `lcs(q, q + w)` and `lcp(q, q + w)`. ```cp // Every square AA of half-length w straddles a unique (q, q + w) with w | q. // lcs and lcp give the exact interval of starts; difference arrays accumulate // squares starting and ending at each position. use std.strings.{RollingHash} use std.seq.{scan} @!multitest let s: Str = read() let n = s.len let h = RollingHash(s) var starts = List.filled(n + 1, 0) var ends = List.filled(n + 1, 0) for w in 1..=n / 2: for k in 0..(n - 1) / w: let q = k * w let lo = max(q - h.lcs(q, q + w), q - w + 1) let hi = min(q, q - w + h.lcp(q, q + w)) if lo > hi: continue starts[lo] += 1 starts[hi + 1] -= 1 ends[lo + 2 * w - 1] += 1 ends[hi + 2 * w] -= 1 let (begun, ended) = (scan(starts, +), scan(ends, +)) print(sum(ended[i] * begun[i + 1] for i in 0..n - 1)) ``` ### 5.4 SAC 2022 CC3 P5 — Multi-Pattern Dictionary (`sac22cc3p5`) Given `n` case-insensitive words and `m` texts, print for each text how many distinct dictionary words appear in it. ```cp // Build one Aho-Corasick automaton over lowercase letters; for each text, // count how many patterns have a non-zero occurrence count. use std.strings.{AhoCorasick, lower} domain Letter = 'a'..='z' fn to_letters(s: Str) -> List = [Letter(c.lower) for c in s] let (n, m): (Int, Int) = read() let words = [to_letters(read::()) for _ in 0..n] let ac = AhoCorasick(words) repeat m: let text = to_letters(read::()) print(count(c > 0 for c in ac.counts(text))) ``` ### 5.5 Palindrome Factorization (CF 932G / Palindromic Partition DP) Minimum number of palindromic pieces to partition a string `s` of length `n` (`n <= 5 * 10^5`). `PalindromicTree` maintains series links so every palindromic suffix of `s[..=i]` is grouped into `O(log n)` arithmetic progressions of lengths, giving O(n log n) DP. ```cp // Group palindromic suffixes by arithmetic progression via series_link: // series_dp[v] caches the minimum dp over v's progression, updated in O(1). use std.strings.{PalindromicTree} domain Letter = 'a'..='z' let s: Str = read() let n = s.len var pt = PalindromicTree() var dp = List.filled(n + 1, n + 1) var series_dp = List.filled(n + 3, n + 1) dp[0] = 0 for i in 0..n: var v = pt.push(Letter(s[i])) while pt.pal_len(v) > 0: series_dp[v] = dp[i + 1 - pt.pal_len(pt.series_link(v)) - pt.diff(v)] if pt.diff(v) == pt.diff(pt.link(v)): series_dp[v] min= series_dp[pt.link(v)] dp[i + 1] min= series_dp[v] + 1 v = pt.series_link(v) print(dp[n]) ``` ## 6. Open questions and core dependencies 1. **Nominal `Rank` domain on `SuffixArray`.** Today `SuffixArray.sa` and `rank` use `Int` because structs cannot yet hold a fresh existential domain field (`domain Rank`). Keeping `sa`, `rank`, and `lcp` as `List` works today and composes cleanly with `domain Rank = 0..n` in user code. 2. **Single-mod `2^61 - 1` hashing (`T2`).** Once `Mod

` uses `mul_mod` for `P > 3 * 10^9`, `HashVal` could optionally narrow from two 31-bit halves to one 61-bit residue, halving register pressure while keeping the same API. ## Coverage Audit against AtCoder Library (`string`), KACTL (`strings`), cp-algorithms (`string`), and strong contestant templates (Benq, jiangly, ecnerwala, tourist). Status: `have` (implemented body in `spec/std/strings.cp`), `new` (`= todo` spec addition), `out` (intentionally omitted). | Reference item | Source(s) | Status | Our name / reason if omitted | | --- | --- | --- | --- | | Basic `Str` ops (`repeat`, `starts_with`, `ends_with`, `find`, `rfind`, `count`) | stdlib | have | `repeat`, `starts_with`, `ends_with`, `find`, `rfind`, `count` (`starts_with`/`ends_with` generalized to `Indexed`) | | ASCII `Char` helpers (`lower`, `upper`, `digit`, predicates) | Contest basics | have / new | `Char.{lower,upper,digit}` (have); `Char.{is_digit,is_lower,is_upper,is_alpha,is_alnum,is_space}` (new) | | `Str` utilities (`to_lower`, `to_upper`, `trim`, `trim_start`, `trim_end`, `split`, `split_once`, `split_whitespace`, `join`, `replace`, `parse_int`) | Contest I/O & parsing | new | `Str.{to_lower,to_upper,trim,split,split_once,split_whitespace,join,replace,parse_int}` | | Z-algorithm | ACL `z_algorithm`, KACTL `Zfunc`, cp-alg | have | `z_function` | | Prefix function / KMP | KACTL `KMP`, cp-alg | have | `prefix_function`, `find_all`, `borders`, `prefix_matches`, `overlap`, `period` | | KMP prefix automaton (O(1) DP transitions) | cp-alg, Benq | new | `KmpAutomaton.{new,len,step,link,find_all}` | | Shift-And / bitset matching | Contest templates | new | `shift_and` | | Wildcard pattern matching (`?`) | cp-alg, contest templates | new | `find_all_wildcard(..., wildcard: Char = '?')` | | Longest common prefix / suffix of two sequences | Contest basics | have | `common_prefix_len`, `common_suffix_len` | | Palindrome check + Manacher | KACTL `Manacher`, cp-alg | have | `is_palindrome`, `manacher`, `Palindromes.{is_palindrome,longest_at,longest_between,longest,count}` | | Lyndon factorization (Duval) | cp-alg | have | `lyndon_factorization` | | Minimum / maximum cyclic rotation | KACTL `MinRotation`, cp-alg | have / new | `min_rotation` (have), `max_rotation` (new) | | Main-Lorentz / Bannai runs (all maximal repetitions) | cp-alg, Bannai | have | `lyndon_runs` | | Suffix array (SA-IS) + Kasai LCP | ACL `suffix_array`/`lcp_array`, KACTL `SuffixArray`, cp-alg | have | `suffix_array(s) -> SuffixArray`, `SuffixArray.{sa,rank,lcp,len,is_empty,lcp_between,rank_range,find_all,count,lcp_range,compare,distinct}` | | Suffix array rank-LCP, prefix-bucket split, k-th distinct substring | KACTL, jiangly, ecnerwala | new | `SuffixArray.{lcp_of_ranks,split,kth_distinct}` | | Compressed suffix tree (from SA + LCP) | KACTL `SuffixTree`, ecnerwala (`ucup5s05f`) | new | `SuffixTreeEdge`, `suffix_tree_edges` | | Double-mod polynomial rolling hash (1D) | cp-alg, Benq, jiangly | have | `HashVal`, `Hashable`, `RollingHash.{new(s, bases:),len,all,slice,get,combine,lcp,lcs,lcp_with}` | | Mersenne `2^61 - 1` rolling hash (1D) | KACTL `Hashing` (mod `2^64-1`/Mersenne), Benq | new | `RollingHash61.{new(s, base:),len,all,slice,get,combine,lcp,lcs,lcp_with}` | | Dynamic rolling hash (point update + range hash, forward & reverse) | Contest templates (SegTree/Fenwick hash) | new | `DynamicHash.{new(seq, bases:),len,is_empty,all,get,set,rev_get,is_palindrome}` | | 2D rolling hash (grid sub-rectangles) | cp-alg, contest templates | have | `Hash2D.{new,rect}` | | Suffix automaton (SAM) + online/generalized + k-th substring | cp-alg, Benq, jiangly | have / new | `SuffixAutomaton.{new,of,push,root,len,step,link,longest,shortest,first_pos,find,contains,distinct,topo_order,occ_counts,lcs}` (have); `{reset,add_word,kth_substring}` (new) | | Palindromic tree (eertree) + series_link + deque/rollback/min-partition | cp-alg, Benq, jiangly | have / new | `PalindromicTree.{new,of,push,len,pal_len,link,step,diff,series_link,occ_counts}` (have); `{push_front,pop,last_state,contains,min_palindrome_partition}` (new) | | Prefix trie + order statistics | cp-alg, contest templates | have / new | `Trie.{new,root,len,step,find,add,remove,count,count_prefix,ends_at,pass_at}` (have); `{contains,clear,kth,count_less}` (new) | | Binary XOR trie (max/min XOR, count `< limit`, k-th XOR) | Benq, jiangly, cp-alg | out | Owned by `std.bitset` (`std.bitset.XorTrie`). | | Aho-Corasick (static) | KACTL `AhoCorasick`, cp-alg | have / new | `AhoCorasick.{new,root,len,step,link,hit,words_at,find_all,counts}` (have); `{fail_order,exit_link,pattern_state}` (new) | | Dynamic / online Aho-Corasick (log-decomposed buckets) | cp-alg, contest templates | new | `DynamicAhoCorasick.{new,add,remove,count_matches}` | | `HashInterval` single-mod `2^64` hash | KACTL `Hashing` | out | Omitted because `RollingHash` (double 31-bit salted) and `RollingHash61` (Mersenne `2^61 - 1` salted) cover both fast-32-bit and single-64-bit hashing without hackable power-of-2 mod (Thue-Morse collision). | | Ukkonen online suffix tree | cp-alg | out | Omitted because `SuffixAutomaton` covers online suffix-structure queries in O(1) amortized per char, and `suffix_tree_edges` builds the compressed suffix tree offline in O(n) from SA+LCP. | | Rabin-Karp standalone function | cp-alg | out | Omitted because `find_all` (KMP, deterministic O(n+m)) and `RollingHash` already cover single-pattern and hash-based matching. | | Edit distance / LCS DP | cp-alg | out | Omitted because it is a 10-line problem-specific DP whose weights/tie-breaking/path-recovery vary per problem. | | Suffix array of a tree / persistent trie / persistent SAM | Niche | out | Omitted because tree-SA and persistent automata have problem-specific node payloads; users compose `Trie`/`SuffixAutomaton` or explicit node pools. | | Unicode / regex / locale | General-purpose | out | Out of scope for competitive programming (ASCII bytes and generic `Indexed`/`Seq` sequences). | ### Renames and removals from `stdlib/strings.cp` - **`RollingHash.with_bases(s, bases)` -> removed / folded into `RollingHash.new(s, bases: ?(Int, Int) = None)`:** One constructor with an optional named argument `bases:` instead of two constructors (`new` + `with_bases`), matching `Hash2D.new(g, bases:)`, `RollingHash61.new(s, base:)`, and `DynamicHash.new(s, bases:)`. - **`starts_with` / `ends_with`:** Generalized from `(Str, Str)` to `` so `List`, `[D]T`, `StrView`, and `ListView` share the same name with zero copies. ## Cross-area - **`std.seq`:** `count`, `find`, `rfind`, `starts_with`, `ends_with` overlap conceptually with sequence queries on `List`/`[D]T`. Keeping `starts_with`/`ends_with` generic over `Indexed` avoids duplication; `Str.count(c: Char)` / `Str.find(p)` / `Str.rfind(p)` remain `Str`-specific because they accept a `Str` or `Char` pattern. - **`std.math` / `std.poly`:** `find_all_wildcard` can also be implemented via NTT for large alphabets (O(n log n) vs O(n * |pat| / 64)); the strings spec exposes the single name `find_all_wildcard`, independent of backend. - **`std.bitset`:** Binary `XorTrie` is owned by `std.bitset` rather than `std.strings`; `std.strings.Trie` covers general-alphabet prefix tries. - **`std.segtree`:** `DynamicHash` is a monoid-over-segment-tree hash specialized for string range hashing and palindrome checks; it avoids making users wire up custom `HashMonoid` structs and power tables manually. ## Powers Every power from `spec/core/12-powers.md` (and any gap beyond it) needed by `spec/std/strings.cp`: 1. **W4 (Sequences, views, and index spaces — `Indexed`, `Seq`, `Range`, cut ranges):** - Signatures: `starts_with`, `ends_with`, `z_function`, `prefix_function`, `find_all`, `borders`, `prefix_matches`, `overlap`, `lyndon_factorization`, `min_rotation`, `max_rotation`, `lyndon_runs`, `manacher`, `suffix_array`, `SuffixArray.{rank_range,find_all,count}`, `suffix_tree_edges`, `RollingHash.{new,get}`, `RollingHash61.{new,get}`, `DynamicHash.new`, `SuffixAutomaton.{of,find,contains,lcs,add_word}`, `PalindromicTree.{of,contains}`, `Trie.{find,add,remove,count,count_prefix,contains,count_less}`, `AhoCorasick.{new,find_all,counts}`, `DynamicAhoCorasick.{add,remove,count_matches}`. - Smallest example: `let sa = suffix_array(a)` where `a: [N]Int`, and `h.get(l..r)` where `l, r: N`. 2. **W6 (Generators / `yields`):** - Signatures: `find_all`, `borders`, `KmpAutomaton.find_all`, `shift_and`, `find_all_wildcard`, `SuffixArray.find_all`, `AhoCorasick.find_all`. - Smallest example: `for (at, pat) in ac.find_all(s): if pat == target: break`. 3. **W8 (User places — `get`/`set`):** - Signatures: `DynamicHash.{get,set}` (so `dh[i] = c` updates the hashed element in O(log n) and `dh[l..r]` queries the range hash). - Smallest example: `dh[i] = 'a'; if dh.is_palindrome(l..r): ans += 1`. 4. **W12 (Cost on first `///` line):** - Signatures: All 191 public declarations in `spec/std/strings.cp`. 5. **Defaulted named arguments (Decision 134 / `spec/delta/parser-gaps.md`):** - Signatures: `RollingHash.new(s, bases: ?(Int, Int) = None)`, `RollingHash61.new(s, base: ?Int = None)`, `DynamicHash.new(s, bases: ?(Int, Int) = None)`, `find_all_wildcard(self, pat, wildcard: Char = '?')`. - Smallest example: `let h2 = RollingHash.new(t, bases: h1.bases)`. 6. **Gaps beyond `spec/core/12-powers.md`:** - **Existential / struct-owned domains** (for `SuffixArray` rank domain `sa.Rank` and `SuffixAutomaton`/`PalindromicTree`/`AhoCorasick` state domains): today states and SA ranks are plain `Int`, so `sam.step(v, c)` and `sa.lcp_of_ranks(l, r)` cannot statically distinguish state IDs from string positions. Smallest example: `struct SuffixArray: domain Rank = 0..s.len; sa: [Rank]Int`. - **Constrained alphabet strings `Str of "01?"`** (Decision 134 / `spec/delta/parser-gaps.md`, used by `cf2187d`): syntax-level refinement type rather than a `std.strings` API. - **128-bit modular multiplication primitive (`mul_mod` / `u128`)** for `RollingHash61` (`mod 2^61 - 1`): needed in user/stdlib CP Lang so `RollingHash61` can be written in ordinary CP Lang without compiler privilege. ## Dreams All dreams in `proto/ports/*/dream/` touching strings: - `proto/ports/ecnerwala/dream/cf1943b.cp`: uses `std.strings.manacher` (`Palindromes.is_palindrome`) — in spec (`have`), passes. - `proto/ports/ecnerwala/dream/cf2124d.cp`: uses `std.strings.is_palindrome` — in spec (`have`), passes. - `proto/ports/ecnerwala/dream/cf1909g.cp`: uses `std.strings.{common_prefix_len, common_suffix_len}` — in spec (`have`), passes. - `proto/ports/ecnerwala/dream/ucup5s05f.cp`: imports `std.strings.suffix_tree_edges` — **now in spec (`new`)**; both `std.strings.suffix_tree_edges` and `suffix_tree_edges` errors are resolved (remaining error in `ucup5s05f.cp` is `std.poly.SubproductTree`). - `proto/ports/ecnerwala/dream/cf2187d.cp`: uses `Str of "01?"` (language syntax, Decision 134 in `spec/delta/parser-gaps.md`) and `s.split_once('?')` (**now in spec (`new`)**). --- # algebra URL: /docs/ref/std/algebra Generated from [spec/std/algebra.cp](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/algebra.cp) by `cpl doc --format json`. ## `Monoid` ```cp pub struct Monoid(id: T, op: (T, T) -> T) ``` An associative operation with an identity: the pair `(id, op)`, written `Monoid(id, op)` or, naming both, `Monoid(id: e, op: (a, b) => ...)`. `op(a, b)` folds `a` on the left of `b`, which matters when it does not commute. The laws are checked by `laws_hold(m, samples)`. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/algebra.cp#L15) ### `Monoid.of` ```cp fn of(m: M) -> Monoid ``` The monoid a structure was handed: a `Monoid` is itself, and a bare operator brings its identity: zero for `+`, `^`, `|` and `gcd`, one for `*`, all bits for `&`, and for `min` / `max` the far end of `T` (`None` on a `?T`). Any other fn has no known identity and needs `Monoid(id, op)`. - **cost**: O(1) - **traps**: never (an operator without a known identity is a compile-time error) Examples: - `Monoid.of(+).id == 0` - `Monoid.of(*).op(3, 4) == 12` - `Monoid.of(min).id == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/algebra.cp#L29) ## `Action` ```cp pub struct Action(id: F, compose: (F, F) -> F, apply: (F, T, Int) -> T, over: Monoid) ``` A lazy update `F` on values `T` folded with `over`. Name every argument, in any order, so the roles read at the call site: Action( id: (1, 0), compose: (new_f, old_f) => (new_f.0 * old_f.0, new_f.0 * old_f.1 + new_f.1), apply: (f, val, span) => f.0 * val + f.1 * span, over: +, ) - `id` is the no-op tag (`apply(id, x, len) == x`). - `compose(new_f, old_f)` applies `old_f` first and then `new_f`. - `apply(f, val, span)` returns the folded value `val` of `span` covered leaves after applying `f`. The positional form `Action(id, compose, apply, over: op)` is the same call. A flipped `compose` still type-checks, so check a hand-written action once with `laws_hold(act, T: [...], F: [...])`. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/algebra.cp#L59) ### `Action.new` ```cp fn new(id: F = F.zero, compose: (F, F) -> F = (+), apply: (F, T, Int) -> T, over: M = (+)) -> Action ``` A lazy action of tags `F` on values `T` folded with `over`. `id` is the no-op tag, `compose(new_f, old_f)` applies `old_f` first and then `new_f`, and `apply(f, val, span)` is the folded value of `span` leaves, `val`, after `f`. `id`, `compose` and `over` default to `F.zero`, `F`'s `+` and `T`'s `+`, so an additive tag on sums needs only `apply`. - **cost**: O(1) - **traps**: never (laws are not checked here; use `laws_hold`) Examples: - `Action(apply: (d, x, span) => x + d * span).apply(2, 10, 3) == 16` - `Action(apply: (d, x, span) => x + d * span).compose(2, 5) == 7` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/algebra.cp#L73) ### `Action.of` ```cp fn of(a: A, op: M) -> Action ``` Resolve a stock action (`add`, `assign`, `affine`) or an `Action` against fold `op`. - **cost**: O(1) - **traps**: never [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/algebra.cp#L80) ## `Desc` ```cp pub struct Desc(x ``` `x` with its order reversed. Build it with `desc(x)`. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/algebra.cp#L95) ## `Desc` ```cp impl Ord for Desc ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/algebra.cp#L97) ### `Desc.lt` ```cp fn lt(a, b) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/algebra.cp#L98) ## `Desc` ```cp impl Show for Desc ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/algebra.cp#L100) ### `Desc.show` ```cp fn show(a) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/algebra.cp#L101) ## `Reversible` ```cp pub trait Reversible ``` A folded value that can be read from the other end. A fold along a tree path walks some stretches upwards; `Rooted.fold_path` reverses those with `rev`. A type that does not implement it is its own reverse, which is right for every commutative operation. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/algebra.cp#L115) ### `Reversible.rev` ```cp fn rev(self) -> Self ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/algebra.cp#L116) ## `MaxSub` ```cp pub struct MaxSub(has: Bool, best: Int, total: Int, pre: Int, suf: Int) ``` Maximum non-empty subarray summary (Kadane monoid). Concatenation (`+` or `MaxSub.join`) is associative with identity `MaxSub.empty` in O(1); `s.scale(k)` scales every element by non-negative `k` in O(1). Implements `Reversible` (swapping `pre` and `suf`) for tree-path folds. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/algebra.cp#L138) ### `MaxSub.empty` ```cp fn empty() -> MaxSub ``` The summary of no elements: the identity of `join`. It has no best subarray. - **cost**: O(1) - **traps**: never Examples: - `MaxSub.empty().try_best == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/algebra.cp#L144) ### `MaxSub.of` ```cp fn of(v: Int) -> MaxSub ``` The summary of the single element `v`: best, total, best prefix and best suffix are all `v`. - **cost**: O(1) - **traps**: never Examples: - `MaxSub.of(-3).try_best == Some(-3)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/algebra.cp#L151) ### `MaxSub.join` ```cp fn join(a: MaxSub, b: MaxSub) -> MaxSub ``` The summary of `a`'s elements followed by `b`'s (the same as `a + b`). Associative, with `MaxSub.empty()` as identity; the best subarray may cross the seam (`a.suf + b.pre`). - **cost**: O(1) - **traps**: never (overflow wraps in release, traps in debug) Examples: - `MaxSub.join(MaxSub.of(2), MaxSub.of(-1)).try_best == Some(2)` - `fold(MaxSub.monoid(), [MaxSub.of(v) for v in [2, -5, 3, 1]]).try_best == Some(4)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/algebra.cp#L160) ### `MaxSub.scale` ```cp fn scale(self, k: Int) -> MaxSub ``` The summary of the same elements each multiplied by `k` (the same as `self * k`). Exact because every maximum scales by a non-negative factor; the empty summary stays empty. - **cost**: O(1) - **traps**: when `k < 0` Examples: - `MaxSub.of(-3).scale(2).try_best == Some(-6)` - `MaxSub.of(-3).scale(0).try_best == Some(0)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/algebra.cp#L178) ### `MaxSub.try_best` ```cp fn try_best(self) -> ?Int ``` The largest sum of a non-empty contiguous run of the summarized elements, or `None` for the empty summary. - **cost**: O(1) - **empty**: `None` - **traps**: never Examples: - `MaxSub.join(MaxSub.of(-1), MaxSub.of(-2)).try_best == Some(-1)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/algebra.cp#L190) ### `MaxSub.monoid` ```cp fn monoid() -> Monoid ``` `Monoid(MaxSub.empty(), MaxSub.join)`, for `SegTree` and `fold`. - **cost**: O(1) - **traps**: never Examples: - `MaxSub.monoid().id.try_best == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/algebra.cp#L197) ## `MaxSub` ```cp impl Add for MaxSub ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/algebra.cp#L199) ### `MaxSub.add` ```cp fn add(a, b) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/algebra.cp#L200) ## `MaxSub` ```cp impl Mul for MaxSub ``` O(1). Scale every underlying value by `k >= 0`. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/algebra.cp#L203) ### `MaxSub.mul` ```cp fn mul(self, k: Int) -> MaxSub ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/algebra.cp#L204) ## `MaxSub` ```cp impl Reversible for MaxSub ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/algebra.cp#L206) ### `MaxSub.rev` ```cp fn rev(self) -> MaxSub ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/algebra.cp#L207) ## `Semigroup` ```cp pub struct Semigroup(op: (T, T) -> T) ``` O(1) construction. Associative operation without an identity, for non-empty folds (`SparseTable`, `DisjointSparseTable`, `SegTree.try_fold`). [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/algebra.cp#L211) ## `Group` ```cp pub struct Group(id: T, op: (T, T) -> T, inv: T -> T) ``` O(1) construction. Associative operation with identity and inverse (`inv`), for generalized Fenwick trees and difference structures. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/algebra.cp#L216) ### `Group.of` ```cp fn of(g: G) -> Group ``` The group a structure was handed: a `Group` is itself, `+` brings zero and negation, `^` brings zero and itself as inverse. Any other fn needs `Group(id, op, inv)`. - **cost**: O(1) - **traps**: never (an operator without a known inverse is a compile-time error) Examples: - `Group.of(+).inv(5) == -5` - `Group.of(^).inv(5) == 5` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/algebra.cp#L228) ## `MinCount` ```cp pub struct MinCount(val: T, count: Int) ``` O(1) per merge. Minimum value together with its multiplicity, for counting zeros or minimum-covered cells under range add (`AddMinCount`). [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/algebra.cp#L246) ### `MinCount.of` ```cp fn of(v: T) -> MinCount ``` The summary of the single element `v`: value `v`, count 1. - **cost**: O(1) - **traps**: never Examples: - `MinCount.of(5).count == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/algebra.cp#L252) ### `MinCount.join` ```cp fn join(a: MinCount, b: MinCount) -> MinCount ``` The smaller value with its count; on equal values, the value with both counts summed. - **cost**: O(1) - **ties**: equal values merge; their counts add - **traps**: never Examples: - `MinCount.join(MinCount.of(2), MinCount.of(2)).count == 2` - `MinCount.join(MinCount(1, 3), MinCount(2, 5)).val == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/algebra.cp#L261) ### `MinCount.monoid` ```cp fn monoid() -> Monoid> ``` `Monoid(id, MinCount.join)` with identity value the far end of `T` (as `Monoid.of(min)`) and count 0, for `SegTree` and `fold`. - **cost**: O(1) - **traps**: never Examples: - `fold(MinCount.monoid(), [MinCount.of(v) for v in [3, 1, 1]]).count == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/algebra.cp#L270) ## `MaxCount` ```cp pub struct MaxCount(val: T, count: Int) ``` O(1) per merge. Maximum value together with its multiplicity (range add: `SegTree(MaxCount.monoid, a, act: add)`). [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/algebra.cp#L273) ### `MaxCount.of` ```cp fn of(v: T) -> MaxCount ``` The summary of the single element `v`: value `v`, count 1. - **cost**: O(1) - **traps**: never Examples: - `MaxCount.of(5).count == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/algebra.cp#L279) ### `MaxCount.join` ```cp fn join(a: MaxCount, b: MaxCount) -> MaxCount ``` The larger value with its count; on equal values, the value with both counts summed. - **cost**: O(1) - **ties**: equal values merge; their counts add - **traps**: never Examples: - `MaxCount.join(MaxCount(4, 1), MaxCount(4, 2)).count == 3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/algebra.cp#L287) ### `MaxCount.monoid` ```cp fn monoid() -> Monoid> ``` `Monoid(id, MaxCount.join)` with identity value the low end of `T` (as `Monoid.of(max)`) and count 0, for `SegTree` and `fold`. - **cost**: O(1) - **traps**: never Examples: - `fold(MaxCount.monoid(), [MaxCount.of(v) for v in [3, 1, 3]]).count == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/algebra.cp#L296) ## `Affine` ```cp pub struct Affine(a: T, b: T) ``` O(1) per composition/eval. Affine map `x -> a * x + b` over any ring `T` (`Int`, `Mod

`). [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/algebra.cp#L299) ### `Affine.id` ```cp fn id() -> Affine ``` The identity map `x -> 1 * x + 0`. - **cost**: O(1) - **traps**: never Examples: - `Affine.id().eval(7) == 7` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/algebra.cp#L305) ### `Affine.eval` ```cp fn eval(self, x: T) -> T ``` `a * x + b`. - **cost**: O(1) - **traps**: never (overflow wraps in release, traps in debug) Examples: - `Affine(2, 3).eval(5) == 13` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/algebra.cp#L312) ### `Affine.then` ```cp fn then(f: Affine, g: Affine) -> Affine ``` `f` first, then `g`: the map `x -> g.eval(f.eval(x))`, which is `Affine(g.a * f.a, g.a * f.b + g.b)`. - **cost**: O(1) - **traps**: never (overflow wraps in release, traps in debug) Examples: - `Affine.then(Affine(2, 0), Affine(1, 1)).eval(5) == 11` - `Affine.then(Affine(1, 1), Affine(2, 0)).eval(5) == 12` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/algebra.cp#L321) ### `Affine.monoid` ```cp fn monoid() -> Monoid> ``` `Monoid(Affine.id(), Affine.then)`: a fold applies the leftmost map first, so a segment tree over maps answers "push `x` through positions `l..r` in order". - **cost**: O(1) - **traps**: never Examples: - `fold(Affine.monoid(), [Affine(1, 1), Affine(2, 0)]).eval(5) == 12` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/algebra.cp#L329) ## `Word` ```cp impl Reversible for Word ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/algebra.cp#L414) ### `Word.rev` ```cp fn rev(self) -> Word ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/algebra.cp#L415) ## `Ordering` ```cp pub enum Ordering ``` O(1). Three-way ordering result returned by `cmp`. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/algebra.cp#L449) ### `Ordering.Less` ```cp Less ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/algebra.cp#L450) ### `Ordering.Equal` ```cp Equal ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/algebra.cp#L451) ### `Ordering.Greater` ```cp Greater ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/algebra.cp#L452) ## `Semiring` ```cp pub struct Semiring(add: A, mul ``` O(1). A semiring from two operation values: `Semiring(min, +)`, `Semiring(or, and)`. `add` is a commutative monoid, `mul` a monoid that distributes over it; zero and one are their identities. Matrix products (`Mat(over:)`), path algebras and `convolve(over:)` take it. `Semiring(+, *)` is the default wherever one is accepted. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/algebra.cp#L468) ## `Op` ```cp pub trait Op ``` An associative operation, possibly without an identity (round 5). Bare operators (`+ * ^ | & min max gcd and or`) implement it. Folds over an `Op` of an empty range return `None`. Law (promised, sampled by stress): `op(op(a, b), c) == op(a, op(b, c))`. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/algebra.cp#L473) ### `Op.op` ```cp fn op(self, a: T, b: T) -> T ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/algebra.cp#L474) ## `HasId` ```cp pub trait HasId ``` The identity of an operation. Law: `op(id, a) == a == op(a, id)`. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/algebra.cp#L477) ### `HasId.id` ```cp fn id(self) -> T ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/algebra.cp#L478) ## `HasInv` ```cp pub trait HasInv ``` The inverse of an operation. Law: `op(a, inv(a)) == id`. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/algebra.cp#L481) ### `HasInv.inv` ```cp fn inv(self, a: T) -> T ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/algebra.cp#L482) ## `Commutative` ```cp pub trait Commutative ``` Law: `op(a, b) == op(b, a)`. Lets folds reorder and tags skip push-down. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/algebra.cp#L485) ## `Idempotent` ```cp pub trait Idempotent ``` Law: `op(a, a) == a`. Lets `SparseTable` overlap halves. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/algebra.cp#L488) ## `Selective` ```cp pub trait Selective ``` Law: `op(a, b)` is `a` or `b`. Lets sliding folds use a monotone deque. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/algebra.cp#L491) ## `AddAction` ```cp pub struct AddAction ``` Marker type for the stock `add` action. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/algebra.cp#L503) ## `AssignAction` ```cp pub struct AssignAction ``` Marker type for the stock `assign` action. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/algebra.cp#L506) ## `AffineAction` ```cp pub struct AffineAction ``` Marker type for the stock `affine` action. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/algebra.cp#L509) ## `FlipAction` ```cp pub struct FlipAction ``` Marker type for the stock `flip` action. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/algebra.cp#L512) ## `add` ```cp pub const add: AddAction = AddAction() ``` Stock action: add a tag to every element. On `+` a span of `n` changes by `f * n`; on `min`/`max` by `f`. Tags commute, so a `SegTree` with it never pushes down. O(1). [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/algebra.cp#L516) ## `assign` ```cp pub const assign: AssignAction = AssignAction() ``` Stock action: assign a tag to every element (`?T` tags, `None` is no-op). O(1) on `+`, `min`, `max`; O(log n) folding `f` `n` times for other ops. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/algebra.cp#L520) ## `affine` ```cp pub const affine: AffineAction = AffineAction() ``` Stock action: `x -> a * x + b` on `+` folds (span `n`: `a * s + b * n`). Not commutative. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/algebra.cp#L523) ## `flip` ```cp pub const flip: FlipAction = FlipAction() ``` Stock action: swap the two halves of a `Flip` value. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/algebra.cp#L526) --- # bag URL: /docs/ref/std/bag Generated from [spec/std/bag.cp](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp) by `cpl doc --format json`. ## `BagCursor` ```cp pub struct BagCursor(id ``` Read-only handle into a `SortedBag` node, valid until the next mutation. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L6) ## `SortedBag` ```cp pub struct SortedBag ``` An ordered multiset (bag) of `K` backed by a randomized treap over a single flat node array with recycled node slots and parent pointers for O(1) amortized cursor stepping. Keeps one node per distinct key with its multiplicity and subtree element count. `add`, `add_many`, `remove`, `remove_all`, `contains`, `count`, `pop_first`, `pop_last`, `rank`, `nth`, `first_true`, `last_true`, and `cursor_*` are O(log n) expected; `range(r)` returns an O(1) view whose `.first`, `.last`, `.len`, `.is_empty` are O(log n) expected and whose iteration (`for x in b.range(r)` / `.rev`) is O(log n + k); `first`, `last`, `key_of` and `count_of` are O(1); `next_cursor` and `prev_cursor` are O(1) amortized; `len`, `distinct`, `is_empty`, `clear`, and `take` are O(1); `entries`, `entries_rev`, and `to_list` are O(n). Elements are ordered by `K`'s `<`; copies of one key are equal and indistinguishable, so no method here has a tie to break between them. `n` in every cost is `len`. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L30) ### `SortedBag.new` ```cp fn new() -> SortedBag ``` Create an empty `SortedBag`. - **cost**: O(1) - **traps**: never Examples: - `var b: SortedBag = SortedBag(); b.len == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L44) ### `SortedBag.of` ```cp fn of(xs: List) -> SortedBag ``` Build a `SortedBag` containing every element of `xs`. Every copy counts: `SortedBag.of([2, 2])` holds two elements. - **cost**: O(n log n) expected - **empty**: an empty bag - **traps**: never Examples: - `SortedBag.of([3, 1, 3]).to_list() == [1, 3, 3]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L54) ### `SortedBag.len` ```cp fn len(self) -> Int ``` Total number of elements in the bag (counting duplicates). - **cost**: O(1) - **traps**: never Examples: - `SortedBag.of([3, 1, 3]).len == 3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L64) ### `SortedBag.distinct` ```cp fn distinct(self) -> Int ``` Number of distinct keys currently in the bag. - **cost**: O(1) - **traps**: never Examples: - `SortedBag.of([3, 1, 3]).distinct == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L72) ### `SortedBag.is_empty` ```cp fn is_empty(self) -> Bool ``` Whether the bag has no elements. - **cost**: O(1) - **traps**: never Examples: - `SortedBag.of([1]).is_empty == false` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L80) ### `SortedBag.clear` ```cp fn clear(mut self) ``` Remove all elements from the bag. The node array keeps its capacity. - **cost**: O(1) - **traps**: never Examples: - `var b = SortedBag.of([1, 2]); b.clear(); b.len == 0 and b.first == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L90) ### `SortedBag.take` ```cp fn take(mut self) -> SortedBag ``` Move the bag's contents out in O(1), leaving `self` empty. - **cost**: O(1) - **traps**: never Examples: - `var b = SortedBag.of([1, 2]); let t = b.take(); b.is_empty and t.to_list() == [1, 2]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L103) ### `SortedBag.add` ```cp fn add(mut self, x: K) -> Bool ``` Insert one copy of `x` into the bag. Always returns `true`. The `Bool` matches `SortedSet.add`, so code can switch between the two. - **cost**: O(log n) expected - **traps**: never Examples: - `var b: SortedBag = SortedBag(); b.add(3) and b.add(3) and b.count(3) == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L120) ### `SortedBag.add_unique` ```cp fn add_unique(mut self, x: K) -> Bool ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L128) ### `SortedBag.add_many` ```cp fn add_many(mut self, x: K, c: Int) ``` Insert `c >= 0` copies of `x` into the bag. `c == 0` does nothing. - **cost**: O(log n) expected, independent of `c` - **traps**: when `c < 0` Examples: - `var b = SortedBag.of([1]); b.add_many(5, 3); b.len == 4 and b.count(5) == 3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L143) ### `SortedBag.remove` ```cp fn remove(mut self, x: K) -> Bool ``` Remove one copy of `x` if present; returns `true` if a copy was removed. - **cost**: O(log n) expected - **traps**: never Examples: - `var b = SortedBag.of([2, 2]); b.remove(2) and b.count(2) == 1 and not b.remove(7)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L157) ### `SortedBag.remove_all` ```cp fn remove_all(mut self, x: K) -> Int ``` Remove all copies of `x` and return how many were removed. - **cost**: O(log n) expected - **traps**: never Examples: - `var b = SortedBag.of([2, 2, 3]); b.remove_all(2) == 2 and b.to_list() == [3]` - `var b = SortedBag.of([3]); b.remove_all(2) == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L171) ### `SortedBag.count` ```cp fn count(self, x: K) -> Int ``` How many copies of `x` are currently in the bag. - **cost**: O(log n) expected - **traps**: never Examples: - `SortedBag.of([2, 2, 3]).count(2) == 2` - `SortedBag.of([2, 2, 3]).count(4) == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L185) ### `SortedBag.contains` ```cp fn contains(self, x: K) -> Bool ``` Whether at least one copy of `x` is in the bag. `x in b` calls this. - **cost**: O(log n) expected - **traps**: never Examples: - `SortedBag.of([2, 3]).contains(3) == true` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L201) ### `SortedBag.first` ```cp fn first(self) -> ?K ``` The smallest element, or `None` when empty. O(1), kept current by every update. - **cost**: O(1) - **empty**: `None` - **ties**: none: copies of the least key are equal - **traps**: never Examples: - `SortedBag.of([3, 1, 1]).first == Some(1)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L210) ### `SortedBag.last` ```cp fn last(self) -> ?K ``` The largest element, or `None` when empty. O(1), kept current by every update. - **cost**: O(1) - **empty**: `None` - **ties**: none: copies of the greatest key are equal - **traps**: never Examples: - `SortedBag.of([3, 1, 3]).last == Some(3)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L220) ### `SortedBag.pop_first` ```cp fn pop_first(mut self) -> ?K ``` Remove and return one copy of the smallest element, or `None` when empty. - **cost**: O(log n) expected - **empty**: `None` - **traps**: never Examples: - `var b = SortedBag.of([3, 1, 1]); b.pop_first() == Some(1) and b.count(1) == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L229) ### `SortedBag.take_first` ```cp fn take_first(mut self, ok: K -> Bool) -> ?K ``` O(log n). Removes and returns the least element satisfying monotone `ok` (false then true): "the shortest partner that completes this chain". One copy is removed. `None`, and no change, when `ok` holds for no element. It is `first_true(ok)` followed by `remove` of the result, in one descent. - **cost**: O(log n) expected - **empty**: `None` - **ties**: none: copies of the answer are equal; one is removed - **traps**: never in release; debug traps when `ok` is not false-then-true at the answer Examples: - `var b = SortedBag.of([1, 4, 4, 6]); b.take_first(x => x >= 3) == Some(4) and b.to_list() == [1, 4, 6]` - `var b = SortedBag.of([1]); b.take_first(x => x >= 3) == None and b.len == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L247) ### `SortedBag.drain_range` ```cp fn drain_range(mut self, r: Range) -> yields K ``` O(log n + k). Removes the elements whose value lies in `r`, yielding them in order. Each copy is yielded once, so a key with count `c` is yielded `c` times. A loop that stops early leaves the elements not yet yielded in the bag. `r` may be any ordered range (`a..b`, `a..=b`, `..b`, `a..`, `..`). - **cost**: O(log n + k) expected for `k` removed - **empty**: yields nothing, for an empty bag or an empty `r` - **order**: ascending - **traps**: never Examples: - `var b = SortedBag.of([1, 3, 3, 5, 7]); b.drain_range(3..6).collect() == [3, 3, 5] and b.to_list() == [1, 7]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L263) ### `SortedBag.pop_last` ```cp fn pop_last(mut self) -> ?K ``` Remove and return one copy of the largest element, or `None` when empty. - **cost**: O(log n) expected - **empty**: `None` - **traps**: never Examples: - `var b = SortedBag.of([3, 3, 1]); b.pop_last() == Some(3) and b.to_list() == [1, 3]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L275) ### `SortedBag.rank` ```cp fn rank(self, k: K) -> Int ``` Number of elements strictly less than `k` (counting duplicates). `k` need not be in the bag. `b.nth(b.rank(k))` is the least element `>= k`. - **cost**: O(log n) expected - **empty**: `0` - **traps**: never Examples: - `SortedBag.of([1, 2, 2, 5]).rank(2) == 1` - `SortedBag.of([1, 2, 2, 5]).rank(3) == 3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L290) ### `SortedBag.rank_le` ```cp fn rank_le(self, k: K) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L303) ### `SortedBag.lo_ok` ```cp fn lo_ok(self, x: K, lo: ?K, lo_inc: Bool) -> Bool ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L316) ### `SortedBag.hi_ok` ```cp fn hi_ok(self, x: K, hi: ?K, hi_inc: Bool) -> Bool ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L322) ### `SortedBag.range` ```cp fn range(self, r: Range) -> SortedRange ``` The keys of `self` inside `r`, as an O(1) view; replaces `first_ge`, `first_gt`, `last_le`, `last_lt` and `count_range` (decision 103). `r` is any ordered range: `a..b`, `a..=b`, `..b`, `..=b`, `a..` or `..`. The view lends `self`, so `self` cannot change while it is in use. - **cost**: O(1) to make; see `SortedRange` for each query - **empty**: a range with no keys gives an empty view - **traps**: never Examples: - `SortedBag.of([1, 3, 3, 7]).range(2..=7).len() == 3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L336) ### `SortedBag.range_first` ```cp fn range_first(self, lo: ?K, lo_inc: Bool, hi: ?K, hi_inc: Bool) -> ?K ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L338) ### `SortedBag.range_last` ```cp fn range_last(self, lo: ?K, lo_inc: Bool, hi: ?K, hi_inc: Bool) -> ?K ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L366) ### `SortedBag.range_len` ```cp fn range_len(self, lo: ?K, lo_inc: Bool, hi: ?K, hi_inc: Bool) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L394) ### `SortedBag.range_each` ```cp fn range_each(self, lo: ?K, lo_inc: Bool, hi: ?K, hi_inc: Bool) -> yields K ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L405) ### `SortedBag.range_each_rev` ```cp fn range_each_rev(self, lo: ?K, lo_inc: Bool, hi: ?K, hi_inc: Bool) -> yields K ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L417) ### `SortedBag.nth` ```cp fn nth(self, i: Int) -> ?K ``` 0-indexed `i`-th smallest element (counting duplicates), or `None` if out of bounds. It is `b.to_list()[i]` without the list; `None` for any `i` outside `0..len`, negative included. - **cost**: O(log n) expected - **empty**: `None` - **traps**: never Examples: - `SortedBag.of([5, 2, 2, 1]).nth(2) == Some(2)` - `SortedBag.of([5, 2, 2, 1]).nth(4) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L439) ### `SortedBag.first_true` ```cp fn first_true(self, ok: K -> Bool) -> ?K ``` Smallest key where monotone `ok(k)` holds (`false..false, true..true`), or `None`. Checks monotonicity at the boundary. O(log n) expected. `ok` is called on keys along one root-to-leaf path. Debug builds check that `ok` is false on the key just below the answer. - **cost**: O(log n) expected calls of `ok` - **empty**: `None` - **ties**: none: copies of a key are one candidate; the least key wins - **traps**: never in release; debug traps when `ok` is not false-then-true at the answer Examples: - `SortedBag.of([1, 4, 6]).first_true(x => x >= 3) == Some(4)` - `SortedBag.of([1, 4, 6]).first_true(x => x > 9) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L468) ### `SortedBag.last_true` ```cp fn last_true(self, ok: K -> Bool) -> ?K ``` Largest key where monotone `ok(k)` holds (`true..true, false..false`), or `None`. Checks monotonicity at the boundary. O(log n) expected. - **cost**: O(log n) expected calls of `ok` - **empty**: `None` - **ties**: none: copies of a key are one candidate; the greatest key wins - **traps**: never in release; debug traps when `ok` is not true-then-false at the answer Examples: - `SortedBag.of([1, 4, 6]).last_true(x => x <= 5) == Some(4)` - `SortedBag.of([1, 4, 6]).last_true(x => x < 1) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L489) ### `SortedBag.drain` ```cp fn drain(mut self; after: ?K = None, before: ?K = None, while ok: K -> Bool) -> List ``` Remove and return the maximal run of elements strictly after `after` (ascending), strictly before `before` (descending), or from the smallest element (ascending) while `ok(k)` holds. O(k log n) expected for `k` removed elements. The walk starts at the first element past the bound and stops at the first element where `ok` is false, which stays; each copy of a removed key is one element of the result. Giving both `after` and `before` is an error. - **cost**: O(k log n) expected for `k` removed elements - **empty**: `[]` - **order**: ascending with `after` or no bound, descending with `before`; a new `List`, keyed from 0 - **traps**: when both `after` and `before` are given Examples: - `var b = SortedBag.of([1, 2, 2, 5, 8]); b.drain(after: 1, while: x => x < 5) == [2, 2] and b.to_list() == [1, 5, 8]` - `var b = SortedBag.of([1, 2, 5, 8]); b.drain(before: 8, while: x => x > 1) == [5, 2] and b.to_list() == [1, 8]` - `var b = SortedBag.of([1, 2, 5]); b.drain(while: x => x < 3) == [1, 2]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L516) ### `SortedBag.cursor_first` ```cp fn cursor_first(self) -> ?BagCursor ``` Cursor to the smallest key, or `None` when empty. - **cost**: O(log n) expected - **empty**: `None` - **traps**: never Examples: - `let b = SortedBag.of([5, 2, 2]); b.key_of(b.cursor_first()!) == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L544) ### `SortedBag.cursor_last` ```cp fn cursor_last(self) -> ?BagCursor ``` Cursor to the largest key, or `None` when empty. - **cost**: O(log n) expected - **empty**: `None` - **traps**: never Examples: - `let b = SortedBag.of([5, 2, 2]); b.key_of(b.cursor_last()!) == 5` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L557) ### `SortedBag.cursor_at` ```cp fn cursor_at(self, k: K) -> ?BagCursor ``` Cursor to exact key `k`, or `None` if absent. - **cost**: O(log n) expected - **empty**: `None` - **traps**: never Examples: - `let b = SortedBag.of([2, 5]); b.cursor_at(5) != None and b.cursor_at(3) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L570) ### `SortedBag.cursor_ge` ```cp fn cursor_ge(self, k: K) -> ?BagCursor ``` Cursor to smallest key `>= k`, or `None`. - **cost**: O(log n) expected - **empty**: `None` - **traps**: never Examples: - `let b = SortedBag.of([2, 5]); b.key_of(b.cursor_ge(3)!) == 5 and b.cursor_ge(6) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L585) ### `SortedBag.cursor_gt` ```cp fn cursor_gt(self, k: K) -> ?BagCursor ``` Cursor to smallest key `> k`, or `None`. - **cost**: O(log n) expected - **empty**: `None` - **traps**: never Examples: - `let b = SortedBag.of([2, 5]); b.key_of(b.cursor_gt(2)!) == 5 and b.cursor_gt(5) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L603) ### `SortedBag.cursor_le` ```cp fn cursor_le(self, k: K) -> ?BagCursor ``` Cursor to largest key `<= k`, or `None`. - **cost**: O(log n) expected - **empty**: `None` - **traps**: never Examples: - `let b = SortedBag.of([2, 5]); b.key_of(b.cursor_le(4)!) == 2 and b.cursor_le(1) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L621) ### `SortedBag.cursor_lt` ```cp fn cursor_lt(self, k: K) -> ?BagCursor ``` Cursor to largest key `< k`, or `None`. - **cost**: O(log n) expected - **empty**: `None` - **traps**: never Examples: - `let b = SortedBag.of([2, 5]); b.key_of(b.cursor_lt(5)!) == 2 and b.cursor_lt(2) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L639) ### `SortedBag.key_of` ```cp fn key_of(self, c: BagCursor) -> K ``` Key stored at cursor `c`. `c` must come from this bag and no mutation may have happened since it was made. - **cost**: O(1) - **traps**: never in release (a stale cursor reads an unspecified key); debug traps when the node of `c` has been freed Examples: - `let b = SortedBag.of([2, 2, 5]); b.key_of(b.cursor_first()!) == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L658) ### `SortedBag.count_of` ```cp fn count_of(self, c: BagCursor) -> Int ``` Multiplicity stored at cursor `c`. - **cost**: O(1) - **traps**: never in release (a stale cursor reads an unspecified count); debug traps when the node of `c` has been freed Examples: - `let b = SortedBag.of([2, 2, 5]); b.count_of(b.cursor_at(2)!) == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L665) ### `SortedBag.next_cursor` ```cp fn next_cursor(self, c: BagCursor) -> ?BagCursor ``` Cursor to the next larger distinct key, or `None`. Steps over all copies of the current key at once. - **cost**: O(1) amortized, O(log n) worst case - **traps**: never in release; debug traps when the node of `c` has been freed Examples: - `let b = SortedBag.of([2, 2, 5]); b.key_of(b.next_cursor(b.cursor_first()!)!) == 5` - `let b = SortedBag.of([2, 5]); b.next_cursor(b.cursor_last()!) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L675) ### `SortedBag.prev_cursor` ```cp fn prev_cursor(self, c: BagCursor) -> ?BagCursor ``` Cursor to the next smaller distinct key, or `None`. - **cost**: O(1) amortized, O(log n) worst case - **traps**: never in release; debug traps when the node of `c` has been freed Examples: - `let b = SortedBag.of([2, 5, 5]); b.key_of(b.prev_cursor(b.cursor_last()!)!) == 2` - `let b = SortedBag.of([2, 5]); b.prev_cursor(b.cursor_first()!) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L694) ### `SortedBag.entries` ```cp fn entries(self) -> yields (key: K, count: Int) ``` Visit every distinct `(key, count)` in ascending order. - **cost**: O(1) amortized per step - **empty**: yields nothing - **order**: ascending key, one entry per distinct key - **traps**: never Examples: - `[e.key for e in SortedBag.of([5, 2, 2]).entries()] == [2, 5]` - `[e.count for e in SortedBag.of([5, 2, 2]).entries()] == [2, 1]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L715) ### `SortedBag.entries_rev` ```cp fn entries_rev(self) -> yields (key: K, count: Int) ``` Visit every distinct `(key, count)` in descending order. Exactly the reverse of `entries`. - **cost**: O(1) amortized per step - **empty**: yields nothing - **order**: descending key, one entry per distinct key - **traps**: never Examples: - `[e.key for e in SortedBag.of([5, 2, 2]).entries_rev()] == [5, 2]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L730) ### `SortedBag.to_list` ```cp fn to_list(self) -> List ``` Every element in ascending order, repeated by multiplicity. - **cost**: O(n) - **empty**: `[]` - **order**: ascending, each key repeated by its count; a new `List`, keyed from 0 - **traps**: never Examples: - `SortedBag.of([3, 1, 3]).to_list() == [1, 3, 3]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L743) ### `SortedBag.reserve` ```cp fn reserve(mut self, cap: Int) ``` Preallocate treap node pool for at least `cap` distinct keys. - **cost**: O(cap) when the pool grows, O(1) otherwise - **traps**: never Examples: - `var b = SortedBag.of([1]); b.reserve(100); b.to_list() == [1]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L754) ### `SortedBag.split_at` ```cp fn split_at(mut self, k: K) -> SortedBag ``` Split off and return all elements `>= k`, keeping `< k` in `self`. Every copy of a key goes to the same side. The larger side keeps the node array; the smaller side's keys move to a fresh one. - **cost**: O(log n + s log n) expected, `s` the smaller side's distinct keys - **empty**: both sides empty - **traps**: never Examples: - `var b = SortedBag.of([1, 3, 3, 5]); let hi = b.split_at(3); b.to_list() == [1] and hi.to_list() == [3, 3, 5]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L767) ### `SortedBag.join` ```cp fn join(mut self, other: SortedBag) ``` Concatenate `other` onto `self` when every key in `self` is `<` every key in `other`. The inverse of `split_at`. The precondition is checked in O(1) against `self.last` and `other.first`; either side may be empty. - **cost**: O(log n) expected - **traps**: when both are non-empty and `self.last >= other.first` Examples: - `var a = SortedBag.of([1, 2]); a.join(SortedBag.of([4, 4])); a.to_list() == [1, 2, 4, 4]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L792) ### `SortedBag.absorb` ```cp fn absorb(mut self, mut other: SortedBag) ``` Merge all elements of `other` into `self` (small-to-large, emptying `other`). Copies add up: a key with count `a` in `self` and `b` in `other` ends with `a + b`. The smaller bag's elements are inserted into the larger, whichever side that is. - **cost**: O(min(n, m) log(n + m)) expected - **empty**: an empty `other` leaves `self` unchanged - **traps**: never Examples: - `var a = SortedBag.of([1, 3]); var b = SortedBag.of([3, 2]); a.absorb(mut b); a.to_list() == [1, 2, 3, 3] and b.is_empty` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L803) ### `SortedBag.sum` ```cp fn sum(self) -> K ``` Sum of all elements (for additive `K`). O(1) when augmented, O(n) otherwise. Each copy is added. `BagNode` keeps no subtree sum, so this bag is never augmented and the cost is O(n); `AugSortedBag` keeps sums. - **cost**: O(n) - **empty**: `K.zero` - **traps**: never (overflow wraps in release, traps in debug) Examples: - `SortedBag.of([2, 2, 5]).sum() == 9` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L832) ### `SortedBag.refresh` ```cp fn refresh(mut self) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L838) ### `SortedBag.sub_of` ```cp fn sub_of(self, t: Int) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L851) ### `SortedBag.pull` ```cp fn pull(mut self, u: Int) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L855) ### `SortedBag.make_node` ```cp fn make_node(mut self, x: K, c: Int) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L865) ### `SortedBag.insert_at` ```cp fn insert_at(mut self, u: Int, x: K, c: Int, unique: Bool) -> (Int, Bool) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L876) ### `SortedBag.erase_at` ```cp fn erase_at(mut self, u: Int, x: K, all: Bool) -> (Int, Int) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L918) ### `SortedBag.merge` ```cp fn merge(mut self, a: Int, b: Int) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L952) ### `SortedBag.split_lt` ```cp fn split_lt(mut self, t: Int, k: K) -> (Int, Int) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L965) ### `SortedBag.move_out` ```cp fn move_out(mut self, t: Int, mut into: SortedBag) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L978) ## `SortedSet` ```cp pub struct SortedSet ``` An ordered set of unique keys `K` with order statistics (`rank`, `nth`), O(1) key-range views (`range(r)`), and monotone search (`first_true`/`last_true`). Backed by `SortedBag`. All single-key and range-summary operations are O(log n) expected; `range(r)` is O(1); range iteration is O(log n + k); `len`, `is_empty`, `clear`, `take` are O(1); `each`, `each_rev`, and `to_list` are O(n). [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L992) ### `SortedSet.new` ```cp fn new() -> SortedSet ``` Create an empty `SortedSet`. - **cost**: O(1) - **traps**: never Examples: - `var s: SortedSet = SortedSet(); s.len == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1000) ### `SortedSet.of` ```cp fn of(xs: List) -> SortedSet ``` Build a `SortedSet` containing the distinct elements of `xs`. - **cost**: O(n log n) expected - **empty**: an empty set - **traps**: never Examples: - `SortedSet.of([3, 1, 3]).to_list() == [1, 3]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1008) ### `SortedSet.len` ```cp fn len(self) -> Int ``` Number of keys in the set. - **cost**: O(1) - **traps**: never Examples: - `SortedSet.of([3, 1, 3]).len == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1018) ### `SortedSet.is_empty` ```cp fn is_empty(self) -> Bool ``` Whether the set is empty. - **cost**: O(1) - **traps**: never Examples: - `SortedSet.of([1]).is_empty == false` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1026) ### `SortedSet.clear` ```cp fn clear(mut self) ``` Remove all keys from the set. - **cost**: O(1) - **traps**: never Examples: - `var s = SortedSet.of([1, 2]); s.clear(); s.len == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1034) ### `SortedSet.take` ```cp fn take(mut self) -> SortedSet ``` Move all keys out, leaving `self` empty. - **cost**: O(1) - **traps**: never Examples: - `var s = SortedSet.of([1, 2]); let t = s.take(); s.is_empty and t.to_list() == [1, 2]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1041) ### `SortedSet.add` ```cp fn add(mut self, x: K) -> Bool ``` Insert `x` if absent; returns `true` when `x` was newly inserted. - **cost**: O(log n) expected - **traps**: never Examples: - `var s = SortedSet.of([1]); s.add(2) and not s.add(2) and s.len == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1049) ### `SortedSet.remove` ```cp fn remove(mut self, x: K) -> Bool ``` Remove `x` if present; returns `true` if removed. - **cost**: O(log n) expected - **traps**: never Examples: - `var s = SortedSet.of([1, 2]); s.remove(2) and not s.remove(2) and s.to_list() == [1]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1056) ### `SortedSet.set` ```cp fn set(mut self, x: K, on: Bool) ``` Add `x` when `on` is true, or remove it otherwise, matching `Set.set` and `Bitset.set`. - **cost**: O(log n) expected - **traps**: never Examples: - `var s = SortedSet.of([1]); s.set(2, true); s.set(1, false); s.to_list() == [2]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1063) ### `SortedSet.contains` ```cp fn contains(self, x: K) -> Bool ``` Whether `x` is in the set. `x in s` calls this. - **cost**: O(log n) expected - **traps**: never Examples: - `SortedSet.of([1, 4]).contains(4) and not SortedSet.of([1, 4]).contains(2)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1076) ### `SortedSet.first` ```cp fn first(self) -> ?K ``` Smallest key in the set, or `None`. O(1), kept current by every update. - **cost**: O(1) - **empty**: `None` - **ties**: none: keys are distinct - **traps**: never Examples: - `SortedSet.of([4, 1, 9]).first == Some(1)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1085) ### `SortedSet.last` ```cp fn last(self) -> ?K ``` Largest key in the set, or `None`. O(1), kept current by every update. - **cost**: O(1) - **empty**: `None` - **ties**: none: keys are distinct - **traps**: never Examples: - `SortedSet.of([4, 1, 9]).last == Some(9)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1095) ### `SortedSet.pop_first` ```cp fn pop_first(mut self) -> ?K ``` Remove and return the smallest key, or `None`. - **cost**: O(log n) expected - **empty**: `None` - **traps**: never Examples: - `var s = SortedSet.of([4, 1]); s.pop_first() == Some(1) and s.to_list() == [4]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1104) ### `SortedSet.pop_last` ```cp fn pop_last(mut self) -> ?K ``` Remove and return the largest key, or `None`. - **cost**: O(log n) expected - **empty**: `None` - **traps**: never Examples: - `var s = SortedSet.of([4, 1]); s.pop_last() == Some(4) and s.to_list() == [1]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1112) ### `SortedSet.rank` ```cp fn rank(self, k: K) -> Int ``` Number of keys strictly less than `k`. `k` need not be in the set. - **cost**: O(log n) expected - **empty**: `0` - **traps**: never Examples: - `SortedSet.of([1, 4, 9]).rank(4) == 1` - `SortedSet.of([1, 4, 9]).rank(5) == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1123) ### `SortedSet.nth` ```cp fn nth(self, i: Int) -> ?K ``` 0-indexed `i`-th smallest key, or `None` if out of range. `None` for any `i` outside `0..len`, negative included. - **cost**: O(log n) expected - **empty**: `None` - **traps**: never Examples: - `SortedSet.of([9, 1, 4]).nth(1) == Some(4)` - `SortedSet.of([9, 1, 4]).nth(-1) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1134) ### `SortedSet.sum` ```cp fn sum(self, keys: Range = ..) -> K ``` The sum of the elements in `keys` (all of them by default), for additive `K`: `set.sum(..b)` adds everything below `b`. O(log n): subtree sums are kept. `keys` may be any ordered range (`a..b`, `a..=b`, `..b`, `a..`, `..`); its ends need not be in the set. - **cost**: O(log n) expected - **empty**: `K.zero`, for an empty set or an empty `keys` - **traps**: never (overflow wraps in release, traps in debug) Examples: - `SortedSet.of([1, 2, 5]).sum() == 8` - `SortedSet.of([1, 2, 5]).sum(..3) == 3` - `SortedSet.of([1, 2, 5]).sum(2..=5) == 7` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1148) ### `SortedSet.first_true` ```cp fn first_true(self, ok: K -> Bool) -> ?K ``` Smallest key `k` where monotone `ok(k)` holds (`false..false, true..true`), or `None`. - **cost**: O(log n) expected calls of `ok` - **empty**: `None` - **ties**: none: keys are distinct; the least key wins - **traps**: never in release; debug traps when `ok` is not false-then-true at the answer Examples: - `SortedSet.of([1, 4, 6]).first_true(x => x >= 3) == Some(4)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1157) ### `SortedSet.last_true` ```cp fn last_true(self, ok: K -> Bool) -> ?K ``` Largest key `k` where monotone `ok(k)` holds (`true..true, false..false`), or `None`. - **cost**: O(log n) expected calls of `ok` - **empty**: `None` - **ties**: none: keys are distinct; the greatest key wins - **traps**: never in release; debug traps when `ok` is not true-then-false at the answer Examples: - `SortedSet.of([1, 4, 6]).last_true(x => x <= 5) == Some(4)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1167) ### `SortedSet.drain` ```cp fn drain(mut self; after: ?K = None, before: ?K = None, while ok: K -> Bool) -> List ``` Remove and return the maximal run of keys strictly after `after` (ascending), strictly before `before` (descending), or from the smallest key (ascending) while `ok(k)` holds. O(k log n) expected for `k` removed keys. The walk stops at the first key where `ok` is false, which stays. Giving both `after` and `before` is an error. - **cost**: O(k log n) expected for `k` removed keys - **empty**: `[]` - **order**: ascending with `after` or no bound, descending with `before`; a new `List`, keyed from 0 - **traps**: when both `after` and `before` are given Examples: - `var s = SortedSet.of([1, 2, 5, 8]); s.drain(after: 1, while: x => x < 6) == [2, 5] and s.to_list() == [1, 8]` - `var s = SortedSet.of([1, 2, 5, 8]); s.drain(before: 8, while: x => x > 1) == [5, 2]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1183) ### `SortedSet.range` ```cp fn range(self, r: Range) -> SortedRange ``` The keys of `self` inside `r`, as an O(1) view; replaces `first_ge`, `first_gt`, `last_le`, `last_lt` and `count_range` (decision 103). `r` is any ordered range: `a..b`, `a..=b`, `..b`, `..=b`, `a..` or `..`. The view lends `self`, so `self` cannot change while it is in use. - **cost**: O(1) to make; see `SortedRange` for each query - **empty**: a range with no keys gives an empty view - **traps**: never Examples: - `SortedSet.of([1, 3, 7]).range(..7).last() == Some(3)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1193) ### `SortedSet.range_first` ```cp fn range_first(self, lo: ?K, lo_inc: Bool, hi: ?K, hi_inc: Bool) -> ?K ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1195) ### `SortedSet.range_last` ```cp fn range_last(self, lo: ?K, lo_inc: Bool, hi: ?K, hi_inc: Bool) -> ?K ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1197) ### `SortedSet.range_len` ```cp fn range_len(self, lo: ?K, lo_inc: Bool, hi: ?K, hi_inc: Bool) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1199) ### `SortedSet.range_each` ```cp fn range_each(self, lo: ?K, lo_inc: Bool, hi: ?K, hi_inc: Bool) -> yields K ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1201) ### `SortedSet.range_each_rev` ```cp fn range_each_rev(self, lo: ?K, lo_inc: Bool, hi: ?K, hi_inc: Bool) -> yields K ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1204) ### `SortedSet.each` ```cp fn each(self) -> yields K ``` Visit every key in ascending order. `for x in s` uses this. - **cost**: O(1) amortized per step - **empty**: yields nothing - **order**: ascending - **traps**: never Examples: - `SortedSet.of([3, 1, 2]).each().collect() == [1, 2, 3]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1216) ### `SortedSet.each_rev` ```cp fn each_rev(self) -> yields K ``` Visit every key in descending order. - **cost**: O(1) amortized per step - **empty**: yields nothing - **order**: descending - **traps**: never Examples: - `SortedSet.of([3, 1, 2]).each_rev().collect() == [3, 2, 1]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1226) ### `SortedSet.to_list` ```cp fn to_list(self) -> List ``` Return all keys in ascending order as a `List`. - **cost**: O(n) - **empty**: `[]` - **order**: ascending; a new `List`, keyed from 0 - **traps**: never Examples: - `SortedSet.of([3, 1, 2]).to_list() == [1, 2, 3]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1236) ### `SortedSet.reserve` ```cp fn reserve(mut self, cap: Int) ``` Preallocate treap node pool for at least `cap` keys. - **cost**: O(cap) when the pool grows, O(1) otherwise - **traps**: never Examples: - `var s = SortedSet.of([1]); s.reserve(100); s.to_list() == [1]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1243) ### `SortedSet.split_at` ```cp fn split_at(mut self, k: K) -> SortedSet ``` Split off and return all keys `>= k`, keeping `< k` in `self`. - **cost**: O(log n + s log n) expected, `s` the smaller side's size - **empty**: both sides empty - **traps**: never Examples: - `var s = SortedSet.of([1, 3, 5]); let hi = s.split_at(3); s.to_list() == [1] and hi.to_list() == [3, 5]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1252) ### `SortedSet.join` ```cp fn join(mut self, other: SortedSet) ``` Concatenate `other` onto `self` when every key in `self` is `<` every key in `other`. The precondition is checked in O(1) against `self.last` and `other.first`. - **cost**: O(log n) expected - **traps**: when both are non-empty and `self.last >= other.first` Examples: - `var a = SortedSet.of([1, 2]); a.join(SortedSet.of([4])); a.to_list() == [1, 2, 4]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1261) ### `SortedSet.absorb` ```cp fn absorb(mut self, mut other: SortedSet) ``` Merge all keys of `other` into `self` (small-to-large, emptying `other`). A key in both sets appears once. - **cost**: O(min(n, m) log(n + m)) expected - **empty**: an empty `other` leaves `self` unchanged - **traps**: never Examples: - `var a = SortedSet.of([1, 3]); var b = SortedSet.of([3, 2]); a.absorb(mut b); a.to_list() == [1, 2, 3] and b.is_empty` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1271) ## `SortedMap` ```cp pub struct SortedMap ``` Order-statistic ordered map from `K` to `V` backed by a randomized treap. `get`, `set`, `remove`, `rank`, `nth`, `first_ge`/`last_le`, `first_true`/`last_true`, `split_at`, `join` are O(log n). Entries are ordered by key; keys are distinct, so no lookup has a tie to break. Every entry-returning method gives `(key, val)`. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1284) ### `SortedMap.entry` ```cp fn entry(self, k: ?K) -> ?(K, V) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1288) ### `SortedMap.at` ```cp fn at(self, c: ?BagCursor) -> ?(K, V) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1290) ### `SortedMap.new` ```cp fn new() -> SortedMap ``` Create an empty `SortedMap`. - **cost**: O(1) - **traps**: never Examples: - `var m: SortedMap = SortedMap(); m.len == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1297) ### `SortedMap.reserve` ```cp fn reserve(mut self, cap: Int) ``` Preallocate treap node pool for at least `cap` entries. - **cost**: O(cap) when the pool grows, O(1) otherwise - **traps**: never Examples: - `var m: SortedMap = SortedMap(); m.reserve(100); m.is_empty` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1305) ### `SortedMap.len` ```cp fn len(self) -> Int ``` Number of key-value pairs. - **cost**: O(1) - **traps**: never Examples: - `var m: SortedMap = SortedMap(); m.set(1, "a"); m.set(1, "b"); m.len == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1313) ### `SortedMap.is_empty` ```cp fn is_empty(self) -> Bool ``` Whether the map is empty. - **cost**: O(1) - **traps**: never Examples: - `var m: SortedMap = SortedMap(); m.is_empty` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1321) ### `SortedMap.clear` ```cp fn clear(mut self) ``` Remove all entries. - **cost**: O(1) - **traps**: never Examples: - `var m: SortedMap = SortedMap(); m.set(1, "a"); m.clear(); m.get(1) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1329) ### `SortedMap.take` ```cp fn take(mut self) -> SortedMap ``` Move contents out in O(1), leaving `self` empty. - **cost**: O(1) - **traps**: never Examples: - `var m: SortedMap = SortedMap(); m.set(1, "a"); let t = m.take(); m.is_empty and t.get(1) == Some("a")` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1338) ### `SortedMap.get` ```cp fn get(self, k: K) -> ?V ``` Look up `k`, returning `None` if absent. - **cost**: O(log n) expected - **traps**: never Examples: - `var m: SortedMap = SortedMap(); m.set(1, "a"); m.get(1) == Some("a") and m.get(2) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1348) ### `SortedMap.contains` ```cp fn contains(self, k: K) -> Bool ``` Whether `k` is present. - **cost**: O(log n) expected - **traps**: never Examples: - `var m: SortedMap = SortedMap(); m.set(1, "a"); m.contains(1) and not m.contains(2)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1356) ### `SortedMap.set` ```cp fn set(mut self, k: K, v: V) ``` Insert or overwrite `k -> v` (W8 `IndexSet` backing `m[k] = v`). - **cost**: O(log n) expected - **traps**: never Examples: - `var m: SortedMap = SortedMap(); m[1] = "a"; m[1] = "b"; m.get(1) == Some("b")` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1364) ### `SortedMap.remove` ```cp fn remove(mut self, k: K) -> ?V ``` Remove `k` and return its previous value, or `None` if absent. - **cost**: O(log n) expected - **traps**: never Examples: - `var m: SortedMap = SortedMap(); m.set(1, "a"); m.remove(1) == Some("a") and m.remove(1) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1373) ### `SortedMap.first` ```cp fn first(self) -> ?(K, V) ``` Smallest `(key, val)` pair, or `None` if empty. O(1), kept current by every update. - **cost**: O(1) - **empty**: `None` - **ties**: none: keys are distinct - **traps**: never Examples: - `var m: SortedMap = SortedMap(); m.set(3, "c"); m.set(1, "a"); m.first == Some((1, "a"))` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1387) ### `SortedMap.last` ```cp fn last(self) -> ?(K, V) ``` Largest `(key, val)` pair, or `None` if empty. O(1), kept current by every update. - **cost**: O(1) - **empty**: `None` - **ties**: none: keys are distinct - **traps**: never Examples: - `var m: SortedMap = SortedMap(); m.set(3, "c"); m.set(1, "a"); m.last == Some((3, "c"))` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1397) ### `SortedMap.pop_first` ```cp fn pop_first(mut self) -> ?(K, V) ``` Remove and return the smallest `(key, val)` pair, or `None`. - **cost**: O(log n) expected - **empty**: `None` - **traps**: never Examples: - `var m: SortedMap = SortedMap(); m.set(3, "c"); m.set(1, "a"); m.pop_first() == Some((1, "a")) and m.len == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1406) ### `SortedMap.pop_last` ```cp fn pop_last(mut self) -> ?(K, V) ``` Remove and return the largest `(key, val)` pair, or `None`. - **cost**: O(log n) expected - **empty**: `None` - **traps**: never Examples: - `var m: SortedMap = SortedMap(); m.set(3, "c"); m.set(1, "a"); m.pop_last() == Some((3, "c")) and m.len == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1417) ### `SortedMap.first_ge` ```cp fn first_ge(self, k: K) -> ?(K, V) ``` Smallest entry with key `>= k`, or `None`. - **cost**: O(log n) expected - **empty**: `None` - **ties**: none: keys are distinct - **traps**: never Examples: - `var m: SortedMap = SortedMap(); m.set(1, "a"); m.set(3, "c"); m.first_ge(2) == Some((3, "c")) and m.first_ge(3) == Some((3, "c"))` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1429) ### `SortedMap.first_gt` ```cp fn first_gt(self, k: K) -> ?(K, V) ``` Smallest entry with key `> k`, or `None`. - **cost**: O(log n) expected - **empty**: `None` - **ties**: none: keys are distinct - **traps**: never Examples: - `var m: SortedMap = SortedMap(); m.set(1, "a"); m.set(3, "c"); m.first_gt(1) == Some((3, "c")) and m.first_gt(3) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1439) ### `SortedMap.last_le` ```cp fn last_le(self, k: K) -> ?(K, V) ``` Largest entry with key `<= k`, or `None`. - **cost**: O(log n) expected - **empty**: `None` - **ties**: none: keys are distinct - **traps**: never Examples: - `var m: SortedMap = SortedMap(); m.set(1, "a"); m.set(3, "c"); m.last_le(2) == Some((1, "a")) and m.last_le(0) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1449) ### `SortedMap.last_lt` ```cp fn last_lt(self, k: K) -> ?(K, V) ``` Largest entry with key `< k`, or `None`. - **cost**: O(log n) expected - **empty**: `None` - **ties**: none: keys are distinct - **traps**: never Examples: - `var m: SortedMap = SortedMap(); m.set(1, "a"); m.set(3, "c"); m.last_lt(3) == Some((1, "a")) and m.last_lt(1) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1459) ### `SortedMap.rank` ```cp fn rank(self, k: K) -> Int ``` Number of entries with key strictly less than `k`. - **cost**: O(log n) expected - **empty**: `0` - **traps**: never Examples: - `var m: SortedMap = SortedMap(); m.set(1, "a"); m.set(3, "c"); m.rank(3) == 1 and m.rank(9) == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1468) ### `SortedMap.nth` ```cp fn nth(self, i: Int) -> ?(K, V) ``` The `i`-th entry in key order (0-based), or `None`. `None` for any `i` outside `0..len`, negative included. - **cost**: O(log n) expected - **empty**: `None` - **traps**: never Examples: - `var m: SortedMap = SortedMap(); m.set(3, "c"); m.set(1, "a"); m.nth(1) == Some((3, "c")) and m.nth(2) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1479) ### `SortedMap.first_true` ```cp fn first_true(self, ok: (K, V) -> Bool) -> ?(K, V) ``` Smallest entry where monotone `ok(k, v)` becomes true, or `None`. `ok` must be false-then-true along ascending keys. - **cost**: O(log n) expected calls of `ok` - **empty**: `None` - **ties**: none: keys are distinct; the least key wins - **traps**: never in release; debug traps when `ok` is not false-then-true at the answer Examples: - `var m: SortedMap = SortedMap(); m.set(1, 10); m.set(4, 40); m.set(6, 60); m.first_true((k, v) => v >= 30) == Some((4, 40))` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1491) ### `SortedMap.last_true` ```cp fn last_true(self, ok: (K, V) -> Bool) -> ?(K, V) ``` Largest entry where monotone `ok(k, v)` still holds, or `None`. `ok` must be true-then-false along ascending keys. - **cost**: O(log n) expected calls of `ok` - **empty**: `None` - **ties**: none: keys are distinct; the greatest key wins - **traps**: never in release; debug traps when `ok` is not true-then-false at the answer Examples: - `var m: SortedMap = SortedMap(); m.set(1, 10); m.set(4, 40); m.set(6, 60); m.last_true((k, v) => k <= 5) == Some((4, 40))` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1503) ### `SortedMap.drain` ```cp fn drain(mut self; after: ?K = None, before: ?K = None, while ok: (K, V) -> Bool) -> List<(K, V)> ``` Remove and return entries after `after` (ascending) or before `before` (descending) while `ok` holds. With neither bound the walk starts at the smallest key. It stops at the first entry where `ok` is false, which stays; bounds are exclusive. Giving both is an error. - **cost**: O(k log n) expected for `k` removed entries - **empty**: `[]` - **order**: ascending key with `after` or no bound, descending with `before`; a new `List`, keyed from 0 - **traps**: when both `after` and `before` are given Examples: - `var m: SortedMap = SortedMap(); m.set(1, 10); m.set(4, 40); m.set(6, 60); m.drain(after: 1, while: (k, v) => v < 50) == [(4, 40)] and m.len == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1516) ### `SortedMap.split_at` ```cp fn split_at(mut self, k: K) -> SortedMap ``` Split off and return all entries with key `>= k`. `self` keeps the entries with key `< k`. - **cost**: O(log n) expected - **empty**: both sides empty - **traps**: never Examples: - `var m: SortedMap = SortedMap(); m.set(1, "a"); m.set(3, "c"); let hi = m.split_at(2); m.len == 1 and hi.first == Some((3, "c"))` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1530) ### `SortedMap.join` ```cp fn join(mut self, other: SortedMap) ``` Concatenate `other` onto `self` when every key in `self` is `<` every key in `other`. The precondition is checked in O(1) against the last key of `self` and the first of `other`. - **cost**: O(log n) expected - **traps**: when both are non-empty and the last key of `self` is `>=` the first key of `other` Examples: - `var a: SortedMap = SortedMap(); a.set(1, "a"); var b: SortedMap = SortedMap(); b.set(3, "c"); a.join(b); a.len == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1540) ### `SortedMap.absorb` ```cp fn absorb(mut self, mut other: SortedMap, join: ?((V, V) -> V) = None) ``` Merge all entries of `other` into `self` (emptying `other`), combining collisions with `join` or overwriting. For a key in both maps the result is `join(self's value, other's value)`, or `other`'s value when `join` is `None`, whichever map is drained into the other. - **cost**: O(min(n, m) log(n + m)) expected - **empty**: an empty `other` leaves `self` unchanged - **traps**: never Examples: - `var a: SortedMap = SortedMap(); a.set(1, 10); var b: SortedMap = SortedMap(); b.set(1, 5); b.set(2, 7); a.absorb(mut b, join: (x, y) => x + y); a.get(1) == Some(15) and a.get(2) == Some(7) and b.is_empty` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1551) ### `SortedMap.items` ```cp fn items(self) -> yields (K, V) ``` O(1) to make. Yields `(key, val)` pairs in ascending key order. - **cost**: O(1) to make, O(1) amortized per step - **empty**: yields nothing - **order**: ascending key - **traps**: never Examples: - `var m: SortedMap = SortedMap(); m.set(3, "c"); m.set(1, "a"); m.items.collect() == [(1, "a"), (3, "c")]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1575) ### `SortedMap.each_rev` ```cp fn each_rev(self) -> yields (K, V) ``` Yield `(key, val)` pairs in descending key order. - **cost**: O(1) amortized per step - **empty**: yields nothing - **order**: descending key - **traps**: never Examples: - `var m: SortedMap = SortedMap(); m.set(3, "c"); m.set(1, "a"); m.each_rev().collect() == [(3, "c"), (1, "a")]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1585) ### `SortedMap.keys` ```cp fn keys(self) -> yields K ``` - **cost**: O(1) to make, O(1) amortized per step - **empty**: yields nothing - **order**: ascending key - **traps**: never Examples: - `var m: SortedMap = SortedMap(); m.set(3, "c"); m.set(1, "a"); m.keys.collect() == [1, 3]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1595) ### `SortedMap.values` ```cp fn values(self) -> yields V ``` - **cost**: O(1) to make, O(1) amortized per step - **empty**: yields nothing - **order**: ascending key - **traps**: never Examples: - `var m: SortedMap = SortedMap(); m.set(3, "c"); m.set(1, "a"); m.values.collect() == ["a", "c"]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1605) ## `AugSortedBag` ```cp pub struct AugSortedBag ``` Monoid-augmented ordered multiset maintaining `op` over `leaf(k)` on every subtree (W10 operation values). Supports O(log n) `add`, `remove`, `rank`, `nth`, `fold_lt`, `fold_le`, `fold_ge`, `fold_gt`, `fold_between`, and O(1) `all`. Every fold combines `leaf(k)` over the chosen elements in ascending key order, one `leaf(k)` per copy, starting from `id`; `op` need not be commutative. An empty selection folds to `id`. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1613) ### `AugSortedBag.sub` ```cp fn sub(self, t: Int) -> T ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1629) ### `AugSortedBag.size` ```cp fn size(self, t: Int) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1630) ### `AugSortedBag.pull` ```cp fn pull(mut self, t: Int) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1632) ### `AugSortedBag.split` ```cp fn split(mut self, t: Int, x: K) -> (Int, Int) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1637) ### `AugSortedBag.merge` ```cp fn merge(mut self, a: Int, b: Int) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1650) ### `AugSortedBag.drop_min` ```cp fn drop_min(mut self, t: Int) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1662) ### `AugSortedBag.extreme` ```cp fn extreme(self, right: Bool) -> ?K ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1668) ### `AugSortedBag.rank_le` ```cp fn rank_le(self, k: K) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1674) ### `AugSortedBag.fold_from` ```cp fn fold_from(self, start: Int, lo: K, strict: Bool) -> T ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1683) ### `AugSortedBag.fold_upto` ```cp fn fold_upto(self, start: Int, hi: K, strict: Bool) -> T ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1692) ### `AugSortedBag.new` ```cp fn new(op: (T, T) -> T, id: T, leaf: K -> T) -> AugSortedBag ``` Create an empty `AugSortedBag` with associative `op`, identity `id`, and key map `leaf`. - **cost**: O(1) - **traps**: never Examples: - `var b: AugSortedBag = AugSortedBag((x, y) => x + y, 0, k => k); b.all == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1706) ### `AugSortedBag.reserve` ```cp fn reserve(mut self, cap: Int) ``` Preallocate treap node pool for at least `cap` elements. - **cost**: O(cap) when the pool grows, O(1) otherwise - **traps**: never Examples: - `var b: AugSortedBag = AugSortedBag((x, y) => x + y, 0, k => k); b.reserve(100); b.len == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1713) ### `AugSortedBag.len` ```cp fn len(self) -> Int ``` Total number of elements (with multiplicity). - **cost**: O(1) - **traps**: never Examples: - `var b: AugSortedBag = AugSortedBag((x, y) => x + y, 0, k => k); b.add(3); b.add(3); b.len == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1721) ### `AugSortedBag.is_empty` ```cp fn is_empty(self) -> Bool ``` Whether the bag is empty. - **cost**: O(1) - **traps**: never Examples: - `var b: AugSortedBag = AugSortedBag((x, y) => x + y, 0, k => k); b.is_empty` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1728) ### `AugSortedBag.all` ```cp fn all(self) -> T ``` Fold of all elements in the bag. - **cost**: O(1) - **empty**: `id` - **traps**: never Examples: - `var b: AugSortedBag = AugSortedBag((x, y) => x + y, 0, k => k); b.add(3); b.add(1); b.add(3); b.all == 7` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1736) ### `AugSortedBag.add` ```cp fn add(mut self, x: K) ``` Insert one copy of `x`. - **cost**: O(log n) expected - **traps**: never Examples: - `var b: AugSortedBag = AugSortedBag((x, y) => x + y, 0, k => k); b.add(3); b.add(3); b.count(3) == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1743) ### `AugSortedBag.remove` ```cp fn remove(mut self, x: K) -> Bool ``` Remove one copy of `x`; returns false if absent. - **cost**: O(log n) expected - **traps**: never Examples: - `var b: AugSortedBag = AugSortedBag((x, y) => x + y, 0, k => k); b.add(3); b.add(1); b.add(3); b.remove(3) and b.all == 4 and not b.remove(2)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1763) ### `AugSortedBag.count` ```cp fn count(self, x: K) -> Int ``` Multiplicity of `x`. - **cost**: O(log n) expected - **traps**: never Examples: - `var b: AugSortedBag = AugSortedBag((x, y) => x + y, 0, k => k); b.add(3); b.add(3); b.count(3) == 2 and b.count(1) == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1778) ### `AugSortedBag.rank` ```cp fn rank(self, k: K) -> Int ``` Number of elements strictly less than `k`. - **cost**: O(log n) expected - **empty**: `0` - **traps**: never Examples: - `var b: AugSortedBag = AugSortedBag((x, y) => x + y, 0, k => k); b.add(3); b.add(1); b.add(3); b.rank(3) == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1786) ### `AugSortedBag.nth` ```cp fn nth(self, i: Int) -> ?K ``` The `i`-th smallest element (0-based), or `None`. Copies count; `None` for any `i` outside `0..len`. - **cost**: O(log n) expected - **empty**: `None` - **traps**: never Examples: - `var b: AugSortedBag = AugSortedBag((x, y) => x + y, 0, k => k); b.add(3); b.add(1); b.add(3); b.nth(2) == Some(3) and b.nth(3) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1803) ### `AugSortedBag.first` ```cp fn first(self) -> ?K ``` Smallest element, or `None`. O(1), kept current by every update. - **cost**: O(1) - **empty**: `None` - **ties**: none: copies of the least key are equal - **traps**: never Examples: - `var b: AugSortedBag = AugSortedBag((x, y) => x + y, 0, k => k); b.add(3); b.add(1); b.first == Some(1)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1822) ### `AugSortedBag.last` ```cp fn last(self) -> ?K ``` Largest element, or `None`. O(1), kept current by every update. - **cost**: O(1) - **empty**: `None` - **ties**: none: copies of the greatest key are equal - **traps**: never Examples: - `var b: AugSortedBag = AugSortedBag((x, y) => x + y, 0, k => k); b.add(3); b.add(1); b.last == Some(3)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1831) ### `AugSortedBag.fold_lt` ```cp fn fold_lt(self, hi: K) -> T ``` Fold elements with key `< hi`. - **cost**: O(log n) expected - **empty**: `id` - **traps**: never Examples: - `var b: AugSortedBag = AugSortedBag((x, y) => x + y, 0, k => k); b.add(3); b.add(1); b.add(3); b.fold_lt(3) == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1839) ### `AugSortedBag.fold_le` ```cp fn fold_le(self, hi: K) -> T ``` Fold elements with key `<= hi`. - **cost**: O(log n) expected - **empty**: `id` - **traps**: never Examples: - `var b: AugSortedBag = AugSortedBag((x, y) => x + y, 0, k => k); b.add(3); b.add(1); b.add(3); b.fold_le(3) == 7` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1847) ### `AugSortedBag.fold_ge` ```cp fn fold_ge(self, lo: K) -> T ``` Fold elements with key `>= lo`. - **cost**: O(log n) expected - **empty**: `id` - **traps**: never Examples: - `var b: AugSortedBag = AugSortedBag((x, y) => x + y, 0, k => k); b.add(3); b.add(1); b.add(3); b.fold_ge(2) == 6` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1855) ### `AugSortedBag.fold_gt` ```cp fn fold_gt(self, lo: K) -> T ``` Fold elements with key `> lo`. - **cost**: O(log n) expected - **empty**: `id` - **traps**: never Examples: - `var b: AugSortedBag = AugSortedBag((x, y) => x + y, 0, k => k); b.add(3); b.add(1); b.add(3); b.fold_gt(1) == 6 and b.fold_gt(3) == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1863) ### `AugSortedBag.fold_between` ```cp fn fold_between(self, lo: K, hi: K) -> T ``` Fold elements with key in `[lo, hi)`. `lo >= hi` selects nothing and gives `id`. - **cost**: O(log n) expected - **empty**: `id`, also when `lo >= hi` - **traps**: never Examples: - `var b: AugSortedBag = AugSortedBag((x, y) => x + y, 0, k => k); b.add(3); b.add(1); b.add(3); b.fold_between(1, 3) == 1 and b.fold_between(2, 4) == 6` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1873) ### `AugSortedBag.each` ```cp fn each(self) -> yields K ``` Yield all elements in ascending order. - **cost**: O(1) amortized per step - **empty**: yields nothing - **order**: ascending, each key repeated by its count - **traps**: never Examples: - `var b: AugSortedBag = AugSortedBag((x, y) => x + y, 0, k => k); b.add(3); b.add(1); b.add(3); b.each().collect() == [1, 3, 3]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1888) ## `AugSortedSet` ```cp pub struct AugSortedSet ``` Monoid-augmented ordered unique set maintaining `op` over `leaf(k)` on every subtree (W10 operation values). Covers dynamic range sums and consecutive-gap monoids (`cf2066e`) in O(log n). Every fold combines `leaf(k)` over the chosen keys in ascending order, starting from `id`; `op` need not be commutative. An empty selection folds to `id`. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1904) ### `AugSortedSet.new` ```cp fn new(op: (T, T) -> T, id: T, leaf: K -> T) -> AugSortedSet ``` Create an empty `AugSortedSet` with associative `op`, identity `id`, and key map `leaf`. - **cost**: O(1) - **traps**: never Examples: - `var s: AugSortedSet = AugSortedSet((x, y) => x + y, 0, k => k); s.all == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1913) ### `AugSortedSet.reserve` ```cp fn reserve(mut self, cap: Int) ``` Preallocate treap node pool for at least `cap` keys. - **cost**: O(cap) when the pool grows, O(1) otherwise - **traps**: never Examples: - `var s: AugSortedSet = AugSortedSet((x, y) => x + y, 0, k => k); s.reserve(100); s.len == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1920) ### `AugSortedSet.len` ```cp fn len(self) -> Int ``` Number of distinct keys. - **cost**: O(1) - **traps**: never Examples: - `var s: AugSortedSet = AugSortedSet((x, y) => x + y, 0, k => k); s.add(3); s.add(3); s.len == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1927) ### `AugSortedSet.is_empty` ```cp fn is_empty(self) -> Bool ``` Whether the set is empty. - **cost**: O(1) - **traps**: never Examples: - `var s: AugSortedSet = AugSortedSet((x, y) => x + y, 0, k => k); s.is_empty` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1934) ### `AugSortedSet.all` ```cp fn all(self) -> T ``` Fold of all keys in the set. - **cost**: O(1) - **empty**: `id` - **traps**: never Examples: - `var s: AugSortedSet = AugSortedSet((x, y) => x + y, 0, k => k); s.add(3); s.add(1); s.add(3); s.all == 4` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1942) ### `AugSortedSet.add` ```cp fn add(mut self, x: K) -> Bool ``` Insert `x`; returns true if `x` was new. - **cost**: O(log n) expected - **traps**: never Examples: - `var s: AugSortedSet = AugSortedSet((x, y) => x + y, 0, k => k); s.add(3) and not s.add(3)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1949) ### `AugSortedSet.remove` ```cp fn remove(mut self, x: K) -> Bool ``` Remove `x`; returns true if `x` was present. - **cost**: O(log n) expected - **traps**: never Examples: - `var s: AugSortedSet = AugSortedSet((x, y) => x + y, 0, k => k); s.add(3); s.remove(3) and not s.remove(3) and s.all == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1959) ### `AugSortedSet.contains` ```cp fn contains(self, x: K) -> Bool ``` Whether `x` is present. - **cost**: O(log n) expected - **traps**: never Examples: - `var s: AugSortedSet = AugSortedSet((x, y) => x + y, 0, k => k); s.add(3); s.contains(3) and not s.contains(1)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1966) ### `AugSortedSet.rank` ```cp fn rank(self, k: K) -> Int ``` Number of keys strictly less than `k`. - **cost**: O(log n) expected - **empty**: `0` - **traps**: never Examples: - `var s: AugSortedSet = AugSortedSet((x, y) => x + y, 0, k => k); s.add(3); s.add(1); s.rank(3) == 1 and s.rank(4) == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1974) ### `AugSortedSet.nth` ```cp fn nth(self, i: Int) -> ?K ``` The `i`-th smallest key (0-based), or `None`. `None` for any `i` outside `0..len`. - **cost**: O(log n) expected - **empty**: `None` - **traps**: never Examples: - `var s: AugSortedSet = AugSortedSet((x, y) => x + y, 0, k => k); s.add(3); s.add(1); s.nth(1) == Some(3) and s.nth(2) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1984) ### `AugSortedSet.first` ```cp fn first(self) -> ?K ``` Smallest key, or `None`. O(1), kept current by every update. - **cost**: O(1) - **empty**: `None` - **ties**: none: keys are distinct - **traps**: never Examples: - `var s: AugSortedSet = AugSortedSet((x, y) => x + y, 0, k => k); s.add(3); s.add(1); s.first == Some(1)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L1993) ### `AugSortedSet.last` ```cp fn last(self) -> ?K ``` Largest key, or `None`. O(1), kept current by every update. - **cost**: O(1) - **empty**: `None` - **ties**: none: keys are distinct - **traps**: never Examples: - `var s: AugSortedSet = AugSortedSet((x, y) => x + y, 0, k => k); s.add(3); s.add(1); s.last == Some(3)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L2002) ### `AugSortedSet.fold_lt` ```cp fn fold_lt(self, hi: K) -> T ``` Fold keys `< hi`. - **cost**: O(log n) expected - **empty**: `id` - **traps**: never Examples: - `var s: AugSortedSet = AugSortedSet((x, y) => x + y, 0, k => k); s.add(1); s.add(3); s.add(5); s.fold_lt(5) == 4` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L2010) ### `AugSortedSet.fold_le` ```cp fn fold_le(self, hi: K) -> T ``` Fold keys `<= hi`. - **cost**: O(log n) expected - **empty**: `id` - **traps**: never Examples: - `var s: AugSortedSet = AugSortedSet((x, y) => x + y, 0, k => k); s.add(1); s.add(3); s.add(5); s.fold_le(5) == 9` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L2018) ### `AugSortedSet.fold_ge` ```cp fn fold_ge(self, lo: K) -> T ``` Fold keys `>= lo`. - **cost**: O(log n) expected - **empty**: `id` - **traps**: never Examples: - `var s: AugSortedSet = AugSortedSet((x, y) => x + y, 0, k => k); s.add(1); s.add(3); s.add(5); s.fold_ge(3) == 8` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L2026) ### `AugSortedSet.fold_gt` ```cp fn fold_gt(self, lo: K) -> T ``` Fold keys `> lo`. - **cost**: O(log n) expected - **empty**: `id` - **traps**: never Examples: - `var s: AugSortedSet = AugSortedSet((x, y) => x + y, 0, k => k); s.add(1); s.add(3); s.add(5); s.fold_gt(3) == 5` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L2034) ### `AugSortedSet.fold_between` ```cp fn fold_between(self, lo: K, hi: K) -> T ``` Fold keys in `[lo, hi)`. `lo >= hi` selects nothing and gives `id`. - **cost**: O(log n) expected - **empty**: `id`, also when `lo >= hi` - **traps**: never Examples: - `var s: AugSortedSet = AugSortedSet((x, y) => x + y, 0, k => k); s.add(1); s.add(3); s.add(5); s.fold_between(1, 5) == 4 and s.fold_between(4, 2) == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L2044) ### `AugSortedSet.each` ```cp fn each(self) -> yields K ``` Yield all keys in ascending order. - **cost**: O(1) amortized per step - **empty**: yields nothing - **order**: ascending - **traps**: never Examples: - `var s: AugSortedSet = AugSortedSet((x, y) => x + y, 0, k => k); s.add(3); s.add(1); s.each().collect() == [1, 3]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L2053) ## `BucketCount` ```cp pub struct BucketCount ``` O(1) point add, O(sqrt(N)) k-th order statistic over an integer value range `r`. Designed as a Mo's algorithm companion for value-range frequency tables. `N` is `r.len`; the table keeps one count per value and one per block of about `sqrt(N)` values. Writes outside `r` trap; reads outside `r` see a count of 0. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L2061) ### `BucketCount.new` ```cp fn new(r: Range) -> BucketCount ``` O(r.len). Create an empty bucketed frequency table over `r`. - **cost**: O(r.len) - **empty**: an empty `r` gives a table every write traps on - **traps**: never Examples: - `var b = BucketCount(0..10); b.len == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L2075) ### `BucketCount.add` ```cp fn add(mut self, x: Int, delta: Int = 1) ``` O(1). Add `delta` (default 1; may be negative) copies of `x`. A negative `delta` removes copies; the count of `x` may not go below 0. - **cost**: O(1) - **traps**: when `x` is not in `r`; when the count of `x` would become negative Examples: - `var b = BucketCount(0..10); b.add(3); b.add(7, 2); b.count(7) == 2 and b.len == 3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L2088) ### `BucketCount.remove` ```cp fn remove(mut self, x: Int, delta: Int = 1) ``` O(1). Remove `delta` (default 1) copies of `x`. The same as `add(x, -delta)`. - **cost**: O(1) - **traps**: when `x` is not in `r`; when the count of `x` would become negative Examples: - `var b = BucketCount(0..10); b.add(7, 2); b.remove(7); b.count(7) == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L2103) ### `BucketCount.count` ```cp fn count(self, x: Int) -> Int ``` O(1). Multiplicity of `x`. - **cost**: O(1) - **traps**: never; an `x` outside `r` has count 0 Examples: - `var b = BucketCount(0..10); b.add(3); b.count(3) == 1 and b.count(4) == 0 and b.count(99) == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L2111) ### `BucketCount.count_lt` ```cp fn count_lt(self, x: Int) -> Int ``` O(sqrt(N)). Number of elements strictly less than `x`. Any `x` works: below `r` gives 0, at or above `r.end` gives `len`. - **cost**: O(sqrt(N)) - **empty**: `0` - **traps**: never Examples: - `var b = BucketCount(0..10); b.add(3); b.add(7, 2); b.count_lt(7) == 1 and b.count_lt(8) == 3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L2122) ### `BucketCount.kth` ```cp fn kth(self, k: Int) -> Int ``` O(sqrt(N)). The `k`-th smallest element, 0-based like `nth`: `kth(0)` is the smallest. Copies count: with elements `3, 7, 7`, `kth(1)` and `kth(2)` are both `7`. - **cost**: O(sqrt(N)) - **ties**: none: the `k`-th element is one value - **traps**: when `k` is not in `0..len` Examples: - `var b = BucketCount(0..10); b.add(3); b.add(7, 2); b.kth(0) == 3 and b.kth(1) == 7 and b.kth(2) == 7` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L2139) ### `BucketCount.len` ```cp fn len(self) -> Int ``` - **cost**: O(1) - **traps**: never Examples: - `var b = BucketCount(0..10); b.add(4, 3); b.len == 3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L2157) ### `BucketCount.is_empty` ```cp fn is_empty(self) -> Bool ``` O(1). Whether the table is empty. - **cost**: O(1) - **traps**: never Examples: - `var b = BucketCount(0..10); b.add(4); b.remove(4); b.is_empty` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L2165) ### `BucketCount.clear` ```cp fn clear(mut self) ``` O(r.len). Reset all counts to zero. - **cost**: O(r.len) - **traps**: never Examples: - `var b = BucketCount(0..10); b.add(4); b.clear(); b.count(4) == 0 and b.len == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L2173) ## `SortedRange` ```cp pub struct SortedRange ``` The keys of a `SortedBag` or `SortedSet` inside a range, made by `range(r)`. A view: it stores the bounds and lends the container, and allocates nothing. `for x in s.range(r)` iterates `each()`. Copies of one key in a `SortedBag` are all inside or all outside, so nothing here has a tie to break. `n` is the container's `len`, `k` the number of keys visited. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L2361) ### `SortedRange.first` ```cp fn first(self) -> ?K ``` The smallest key in the range. - **cost**: O(log n) expected - **empty**: `None` - **ties**: copies of a key are equal, so any is the answer - **traps**: never Examples: - `SortedSet.of([1, 3, 7]).range(2..).first() == Some(3)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L2374) ### `SortedRange.last` ```cp fn last(self) -> ?K ``` The largest key in the range. - **cost**: O(log n) expected - **empty**: `None` - **ties**: copies of a key are equal, so any is the answer - **traps**: never Examples: - `SortedSet.of([1, 3, 7]).range(..=6).last() == Some(3)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L2383) ### `SortedRange.len` ```cp fn len(self) -> Int ``` The number of keys in the range, counting copies. - **cost**: O(log n) expected - **empty**: 0 - **traps**: never Examples: - `SortedBag.of([1, 3, 3, 7]).range(3..=3).len() == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L2391) ### `SortedRange.is_empty` ```cp fn is_empty(self) -> Bool ``` True when the range holds no key. - **cost**: O(log n) expected - **empty**: `true` - **traps**: never Examples: - `SortedSet.of([1, 7]).range(2..7).is_empty()` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L2399) ### `SortedRange.each` ```cp fn each(self) -> yields K ``` The keys in ascending order, copies included. - **cost**: O(log n + k) expected for `k` keys visited - **empty**: yields nothing - **order**: ascending - **traps**: never Examples: - `SortedBag.of([1, 3, 3, 7]).range(2..).each().collect() == [3, 3, 7]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L2408) ### `SortedRange.rev` ```cp fn rev(self) -> yields K ``` The keys in descending order, copies included. - **cost**: O(log n + k) expected for `k` keys visited - **empty**: yields nothing - **order**: descending - **traps**: never Examples: - `SortedSet.of([1, 3, 7]).range(..7).rev().collect() == [3, 1]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bag.cp#L2417) --- # beats URL: /docs/ref/std/beats Generated from [spec/std/beats.cp](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/beats.cp) by `cpl doc --format json`. ## `BeatsSegTree` ```cp pub struct BeatsSegTree ``` Segment Tree Beats over a domain `D` of `Int` values. Supports `chmin`, `chmax`, `add`, `sum`, `min_val`, `max_val`, and `get`. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/beats.cp#L10) ### `BeatsSegTree.new` ```cp fn new(a: ?[D]Int = None, fill: ?Int = None) -> BeatsSegTree ``` A Segment Tree Beats over `D` holding the values of `a`, or `fill` at every position, or zero everywhere when neither is given. Every node keeps the exact maximum, second maximum and its count, the same for the minimum, and the sum. - **cost**: O(|D|) - **empty**: an empty `D` builds a tree whose sums are zero and whose extrema are `None` - **order**: positions keep the domain `D` (of `a`, when given) - **traps**: when both `a` and `fill` are given Examples: - `BeatsSegTree([5, 1, 4]).all_sum == 10` - `BeatsSegTree<0..3>(fill: 2).all_sum == 6` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/beats.cp#L31) ### `BeatsSegTree.pull` ```cp fn pull(mut self, u: Int) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/beats.cp#L57) ### `BeatsSegTree.build` ```cp fn build(mut self, u: Int, nl: Int, nr: Int, vals: List) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/beats.cp#L85) ### `BeatsSegTree.apply_add` ```cp fn apply_add(mut self, u: Int, len: Int, x: Int) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/beats.cp#L101) ### `BeatsSegTree.apply_chmin` ```cp fn apply_chmin(mut self, u: Int, x: Int) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/beats.cp#L109) ### `BeatsSegTree.apply_chmax` ```cp fn apply_chmax(mut self, u: Int, x: Int) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/beats.cp#L116) ### `BeatsSegTree.push` ```cp fn push(mut self, u: Int, nl: Int, nr: Int) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/beats.cp#L123) ### `BeatsSegTree.chmin_rec` ```cp fn chmin_rec(mut self, u: Int, nl: Int, nr: Int, ql: Int, qr: Int, x: Int) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/beats.cp#L135) ### `BeatsSegTree.chmin` ```cp fn chmin(mut self, r: Range, x: Int) ``` Replace every `a[i]` in `r` with `min(a[i], x)`. Descends only into nodes whose maximum exceeds `x` and whose second maximum does not, where the update is a tag. - **cost**: O(log |D|) amortized; O(log^2 |D|) amortized when mixed with `add` - **empty**: changes nothing - **traps**: when a non-empty `r` reaches outside `D` Examples: - `var t = BeatsSegTree([5, 1, 4]); t.chmin(0..3, 3); t.all_sum == 7` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/beats.cp#L153) ### `BeatsSegTree.chmax_rec` ```cp fn chmax_rec(mut self, u: Int, nl: Int, nr: Int, ql: Int, qr: Int, x: Int) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/beats.cp#L158) ### `BeatsSegTree.chmax` ```cp fn chmax(mut self, r: Range, x: Int) ``` Replace every `a[i]` in `r` with `max(a[i], x)`; the mirror of `chmin`. - **cost**: O(log |D|) amortized; O(log^2 |D|) amortized when mixed with `add` - **empty**: changes nothing - **traps**: when a non-empty `r` reaches outside `D` Examples: - `var t = BeatsSegTree([5, 1, 4]); t.chmax(0..2, 2); t.all_sum == 11` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/beats.cp#L175) ### `BeatsSegTree.add_rec` ```cp fn add_rec(mut self, u: Int, nl: Int, nr: Int, ql: Int, qr: Int, x: Int) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/beats.cp#L180) ### `BeatsSegTree.add` ```cp fn add(mut self, r: Range, x: Int) ``` Add `x` to every `a[i]` in `r`. - **cost**: O(log |D|) - **empty**: changes nothing - **traps**: when a non-empty `r` reaches outside `D` (overflow wraps in release, traps in debug) Examples: - `var t = BeatsSegTree([5, 1, 4]); t.add(1..3, 10); t.sum(0..3) == 30` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/beats.cp#L197) ### `BeatsSegTree.sum_rec` ```cp fn sum_rec(mut self, u: Int, nl: Int, nr: Int, ql: Int, qr: Int) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/beats.cp#L202) ### `BeatsSegTree.sum` ```cp fn sum(mut self, r: Range) -> Int ``` The sum of the current values in `r`. Takes `mut self` because it pushes pending tags. - **cost**: O(log |D|) - **empty**: zero - **traps**: when a non-empty `r` reaches outside `D` Examples: - `BeatsSegTree([5, 1, 4]).sum(1..3) == 5` - `BeatsSegTree([5, 1, 4]).sum(1..1) == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/beats.cp#L216) ### `BeatsSegTree.min_rec` ```cp fn min_rec(mut self, u: Int, nl: Int, nr: Int, ql: Int, qr: Int) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/beats.cp#L221) ### `BeatsSegTree.min_val` ```cp fn min_val(mut self, r: Range) -> ?Int ``` The least current value in `r`, or `None` when `r` is empty. - **cost**: O(log |D|) - **empty**: `None` - **ties**: returns a value, so equal candidates are indistinguishable - **traps**: when a non-empty `r` reaches outside `D` Examples: - `BeatsSegTree([5, 1, 4]).min_val(0..3) == Some(1)` - `BeatsSegTree([5, 1, 4]).min_val(2..2) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/beats.cp#L236) ### `BeatsSegTree.max_rec` ```cp fn max_rec(mut self, u: Int, nl: Int, nr: Int, ql: Int, qr: Int) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/beats.cp#L241) ### `BeatsSegTree.max_val` ```cp fn max_val(mut self, r: Range) -> ?Int ``` The greatest current value in `r`, or `None` when `r` is empty. - **cost**: O(log |D|) - **empty**: `None` - **ties**: returns a value, so equal candidates are indistinguishable - **traps**: when a non-empty `r` reaches outside `D` Examples: - `var t = BeatsSegTree([5, 1, 4]); t.chmin(0..1, 2); t.max_val(0..3) == Some(4)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/beats.cp#L255) ### `BeatsSegTree.get` ```cp fn get(mut self, i: D) -> Int ``` The current value at position `i`. - **cost**: O(log |D|) - **traps**: when `i` is outside `D` Examples: - `BeatsSegTree([5, 1, 4]).get(2) == 4` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/beats.cp#L265) ### `BeatsSegTree.div_rec` ```cp fn div_rec(mut self, u: Int, nl: Int, nr: Int, ql: Int, qr: Int, d: Int, rem: Bool) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/beats.cp#L267) ### `BeatsSegTree.set` ```cp fn set(mut self, i: D, x: Int) ``` Assign `a[i] = x`, replacing whatever earlier updates left there. - **cost**: O(log |D|) - **traps**: when `i` is outside `D` Examples: - `var t = BeatsSegTree([5, 1, 4]); t.set(1, 9); t.all_max == Some(9)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/beats.cp#L287) ### `BeatsSegTree.assign` ```cp fn assign(mut self, r: Range, x: Int) ``` Overwrite every position in `r` with `x`. - **cost**: O(log |D|) amortized - **empty**: changes nothing - **traps**: when a non-empty `r` reaches outside `D` Examples: - `var t = BeatsSegTree([5, 1, 4]); t.assign(0..2, 0); t.all_sum == 4` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/beats.cp#L297) ### `BeatsSegTree.chdiv` ```cp fn chdiv(mut self, r: Range, d: Int) ``` Replace every `a[i]` in `r` with `a[i] / d`, rounding toward negative infinity. A node whose values all map to the same shift becomes a single `add` tag, so each value is divided O(log V) times before it settles, for values of magnitude at most `V`. - **cost**: O(log |D| log V) amortized - **empty**: changes nothing - **traps**: when `d <= 0`, or a non-empty `r` reaches outside `D` Examples: - `var t = BeatsSegTree([5, 1, 4]); t.chdiv(0..3, 2); t.all_sum == 4` - `var t = BeatsSegTree([-3]); t.chdiv(0..1, 2); t.get(0) == -2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/beats.cp#L310) ### `BeatsSegTree.chmod` ```cp fn chmod(mut self, r: Range, m: Int) ``` Replace every `a[i]` in `r` with `a[i] mod m`, the remainder in `0..m` (floored, so negative values map into `0..m` too). Nodes whose maximum is below `m` are skipped. - **cost**: O(log |D| log V) amortized - **empty**: changes nothing - **traps**: when `m <= 0`, or a non-empty `r` reaches outside `D` Examples: - `var t = BeatsSegTree([5, 1, 4]); t.chmod(0..3, 3); t.all_sum == 4` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/beats.cp#L323) ### `BeatsSegTree.all_sum` ```cp fn all_sum(self) -> Int ``` The sum of every current value in `D`. - **cost**: O(1) - **empty**: zero on an empty domain - **traps**: never Examples: - `BeatsSegTree([5, 1, 4]).all_sum == 10` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/beats.cp#L335) ### `BeatsSegTree.all_min` ```cp fn all_min(self) -> ?Int ``` The least current value in `D`, or `None` when `D` is empty. - **cost**: O(1) - **empty**: `None` - **ties**: returns a value, so equal candidates are indistinguishable - **traps**: never Examples: - `BeatsSegTree([5, 1, 4]).all_min == Some(1)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/beats.cp#L345) ### `BeatsSegTree.all_max` ```cp fn all_max(self) -> ?Int ``` The greatest current value in `D`, or `None` when `D` is empty. - **cost**: O(1) - **empty**: `None` - **ties**: returns a value, so equal candidates are indistinguishable - **traps**: never Examples: - `BeatsSegTree([5, 1, 4]).all_max == Some(5)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/beats.cp#L355) ## `HistoricBeatsSegTree` ```cp pub struct HistoricBeatsSegTree ``` O(|D|) space. Segment Tree Beats with historic maximum and historic sum tracking under range `chmin`, `chmax`, and `add` (Ji Driver with historic tags). [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/beats.cp#L360) ### `HistoricBeatsSegTree.new` ```cp fn new(a: ?[D]Int = None, fill: ?Int = None) -> HistoricBeatsSegTree ``` A Beats tree that also tracks history, holding `a`, or `fill` everywhere, or zeros. Each position remembers the greatest value it has held and the running sum of its values over versions; version 0 is the initial array, and every `chmin`, `chmax` or `add` call makes one new version of the whole array. - **cost**: O(|D|) - **empty**: an empty `D` builds a tree whose sums are zero and whose maxima are `None` - **order**: positions keep the domain `D` (of `a`, when given) - **traps**: when both `a` and `fill` are given Examples: - `HistoricBeatsSegTree([1, 2]).hist_sum(0..2) == 3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/beats.cp#L384) ### `HistoricBeatsSegTree.build` ```cp fn build(mut self, u: Int, nl: Int, nr: Int, vals: List) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/beats.cp#L404) ### `HistoricBeatsSegTree.pull` ```cp fn pull(mut self, u: Int) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/beats.cp#L419) ### `HistoricBeatsSegTree.compose` ```cp fn compose(mut self, u: Int, k: Int, a: Int, h: Int, cc: Int) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/beats.cp#L449) ### `HistoricBeatsSegTree.apply` ```cp fn apply(mut self, u: Int, len: Int, a1: Int, h1: Int, c1: Int, a2: Int, h2: Int, c2: Int, a3: Int, h3: Int, c3: Int) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/beats.cp#L455) ### `HistoricBeatsSegTree.give` ```cp fn give(mut self, v: Int, len: Int, u: Int, pmax: Int, pmin: Int) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/beats.cp#L483) ### `HistoricBeatsSegTree.push` ```cp fn push(mut self, u: Int, nl: Int, nr: Int) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/beats.cp#L490) ### `HistoricBeatsSegTree.upd` ```cp fn upd(mut self, u: Int, nl: Int, nr: Int, ql: Int, qr: Int, op: Int, x: Int) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/beats.cp#L503) ### `HistoricBeatsSegTree.update` ```cp fn update(mut self, r: Range, op: Int, x: Int) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/beats.cp#L528) ### `HistoricBeatsSegTree.chmin` ```cp fn chmin(mut self, r: Range, x: Int) ``` Replace every `a[i]` in `r` with `min(a[i], x)`, then record a new version. - **cost**: O(log |D|) amortized; O(log^2 |D|) amortized when mixed with `add` - **empty**: changes no value but still records a version - **traps**: when a non-empty `r` reaches outside `D` Examples: - `var t = HistoricBeatsSegTree([5, 1]); t.chmin(0..2, 2); t.sum(0..2) == 3 and t.hist_max(0..1) == Some(5)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/beats.cp#L539) ### `HistoricBeatsSegTree.chmax` ```cp fn chmax(mut self, r: Range, x: Int) ``` Replace every `a[i]` in `r` with `max(a[i], x)`, then record a new version. - **cost**: O(log |D|) amortized; O(log^2 |D|) amortized when mixed with `add` - **empty**: changes no value but still records a version - **traps**: when a non-empty `r` reaches outside `D` Examples: - `var t = HistoricBeatsSegTree([5, 1]); t.chmax(0..2, 3); t.sum(0..2) == 8` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/beats.cp#L546) ### `HistoricBeatsSegTree.add` ```cp fn add(mut self, r: Range, x: Int) ``` Add `x` to every `a[i]` in `r`, then record a new version. - **cost**: O(log |D|) - **empty**: changes no value but still records a version - **traps**: when a non-empty `r` reaches outside `D` Examples: - `var t = HistoricBeatsSegTree([1, 2]); t.add(0..1, 3); t.sum(0..2) == 6` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/beats.cp#L553) ### `HistoricBeatsSegTree.ask` ```cp fn ask(mut self, u: Int, nl: Int, nr: Int, ql: Int, qr: Int, what: Int) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/beats.cp#L555) ### `HistoricBeatsSegTree.query` ```cp fn query(mut self, r: Range, what: Int) -> ?Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/beats.cp#L565) ### `HistoricBeatsSegTree.sum` ```cp fn sum(mut self, r: Range) -> Int ``` The sum of the current values in `r`. - **cost**: O(log |D|) - **empty**: zero - **traps**: when a non-empty `r` reaches outside `D` Examples: - `HistoricBeatsSegTree([1, 2]).sum(0..2) == 3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/beats.cp#L576) ### `HistoricBeatsSegTree.max_val` ```cp fn max_val(mut self, r: Range) -> ?Int ``` The greatest current value in `r`, or `None` when `r` is empty. - **cost**: O(log |D|) - **empty**: `None` - **ties**: returns a value, so equal candidates are indistinguishable - **traps**: when a non-empty `r` reaches outside `D` Examples: - `var t = HistoricBeatsSegTree([1, 2]); t.add(0..2, 5); t.add(0..2, -10); t.max_val(0..1) == Some(-4)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/beats.cp#L584) ### `HistoricBeatsSegTree.hist_max` ```cp fn hist_max(mut self, r: Range) -> ?Int ``` The greatest value any position in `r` has held in any version, the initial one included; `None` when `r` is empty. - **cost**: O(log |D|) - **empty**: `None` - **ties**: returns a value, so equal candidates are indistinguishable - **traps**: when a non-empty `r` reaches outside `D` Examples: - `var t = HistoricBeatsSegTree([1, 2]); t.add(0..2, 5); t.add(0..2, -10); t.hist_max(0..1) == Some(6)` - `HistoricBeatsSegTree([1, 2]).hist_max(1..1) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/beats.cp#L594) ### `HistoricBeatsSegTree.hist_sum` ```cp fn hist_sum(mut self, r: Range) -> Int ``` The sum over positions `i` in `r` of every value `a[i]` has had, one term per version: the initial array plus the array after each update call. - **cost**: O(log |D|) - **empty**: zero - **traps**: when a non-empty `r` reaches outside `D` Examples: - `var t = HistoricBeatsSegTree([1, 2]); t.add(0..1, 3); t.hist_sum(0..2) == 9` - `var t = HistoricBeatsSegTree([1, 2]); t.add(0..1, 3); t.hist_sum(1..2) == 4` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/beats.cp#L603) --- # bitset URL: /docs/ref/std/bitset Generated from [spec/std/bitset.cp](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp) by `cpl doc --format json`. ## `Bitset` ```cp pub struct Bitset ``` One bit per position of `D`, in `ceil(K / 64)` words. `Bitset` is an explicit type you ask for; `[D]Bool` stays one byte per element and never turns into this behind your back. Single-bit operations are O(1); whole-set operations are O(K / 64). [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L7) ### `Bitset.new` ```cp fn new() -> Bitset ``` The empty set, every word zero; the same set as `empty()`. - **cost**: O(K / 64) time and space - **traps**: never Examples: - `domain D = 0..10; Bitset().len == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L16) ### `Bitset.empty` ```cp fn empty() -> Bitset ``` The empty set, matching `Subset.empty` (a call here: it is O(K / 64)); the same as `new()`. - **cost**: O(K / 64) time and space - **traps**: never Examples: - `domain D = 0..10; Bitset.empty().is_empty` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L24) ### `Bitset.full` ```cp fn full() -> Bitset ``` The full set containing every position of `D`, matching `Subset.full`. No bit past the last position is ever set, so `len` is `D.K`. - **cost**: O(K / 64) time and space - **traps**: never Examples: - `domain D = 0..10; Bitset.full().len == 10` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L32) ### `Bitset.single` ```cp fn single(i: D) -> Bitset ``` The singleton set `{i}`, matching `Subset.single(i)`. - **cost**: O(K / 64) time and space - **traps**: never Examples: - `domain D = 0..10; Bitset.single(D(4)).each().collect() == [D(4)]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L42) ### `Bitset.from` ```cp fn from(a: [D]Bool) -> Bitset ``` The set of positions where `a` is true. - **cost**: O(K) time, O(K / 64) space - **empty**: the empty set when no element is true - **traps**: never Examples: - `domain D = 0..10; Bitset.from([D] v => Int(v) % 4 == 0).each().collect() == [D(0), D(4), D(8)]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L53) ### `Bitset.of` ```cp fn of(xs: List) -> Bitset ``` Build a bitset from a list or generator of positions `D`. Repeated positions are set once. - **cost**: O(K / 64 + xs.len) time, O(K / 64) space - **empty**: the empty set - **traps**: never Examples: - `domain D = 0..10; Bitset.of([D(3), D(1), D(3)]).each().collect() == [D(1), D(3)]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L65) ### `Bitset.contains` ```cp fn contains(self, i: D) -> Bool ``` Whether position `i` is set; `i in b` calls it. - **cost**: O(1) - **traps**: never Examples: - `domain D = 0..10; let b = Bitset.single(D(4)); b.contains(D(4)) and not b.contains(D(5))` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L75) ### `Bitset.add` ```cp fn add(mut self, i: D) -> Bool ``` Set the bit at position `i`; returns `true` if `i` was not already set (matches `Set.add`). - **cost**: O(1) - **traps**: never Examples: - `domain D = 0..10; var b = Bitset(); let x = b.add(D(2)); let y = b.add(D(2)); x and not y and b.len == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L82) ### `Bitset.remove` ```cp fn remove(mut self, i: D) -> Bool ``` Clear the bit at position `i`; returns `true` if `i` was set (matches `Set.remove`). - **cost**: O(1) - **traps**: never Examples: - `domain D = 0..10; var b = Bitset.single(D(2)); let x = b.remove(D(2)); let y = b.remove(D(2)); x and not y and b.is_empty` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L93) ### `Bitset.toggle` ```cp fn toggle(mut self, i: D) ``` Flip the bit at position `i`: set it if clear, clear it if set. - **cost**: O(1) - **traps**: never Examples: - `domain D = 0..10; var b = Bitset.single(D(2)); b.toggle(D(2)); b.toggle(D(5)); b.each().collect() == [D(5)]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L104) ### `Bitset.with` ```cp fn with(self, i: D) -> Bitset ``` A copy of `self` with `i` added; `self` is unchanged. - **cost**: O(K / 64) time and space - **traps**: never Examples: - `domain D = 0..10; Bitset.single(D(1)).with(D(3)).each().collect() == [D(1), D(3)]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L113) ### `Bitset.without` ```cp fn without(self, i: D) -> Bitset ``` A copy of `self` with `i` removed; `self` is unchanged. Removing a non-member copies. - **cost**: O(K / 64) time and space - **traps**: never Examples: - `domain D = 0..10; Bitset.full().without(D(0)).len == 9` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L123) ### `Bitset.set` ```cp fn set(self, i: D, on: Bool) -> Bitset ``` A copy of `self` with `i` added if `on` or removed otherwise, matching `Subset.set`. - **cost**: O(K / 64) time and space - **traps**: never Examples: - `domain D = 0..10; Bitset.single(D(1)).set(D(1), false).is_empty` - `domain D = 0..10; Bitset().set(D(7), true).each().collect() == [D(7)]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L134) ### `Bitset.complement` ```cp fn complement(self) -> Bitset ``` The complement of `self` within `D`, matching `Subset.complement`; bits past the last position stay clear. - **cost**: O(K / 64) time and space - **traps**: never Examples: - `domain D = 0..10; Bitset.of([D(1), D(3), D(8)]).complement().len == 7` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L143) ### `Bitset.clear` ```cp fn clear(mut self) ``` Remove every position from the set. - **cost**: O(K / 64) - **traps**: never Examples: - `domain D = 0..10; var b = Bitset.full(); b.clear(); b.is_empty` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L153) ### `Bitset.any` ```cp fn any(self, pred: D -> Bool) -> Bool ``` True when some position in this set satisfies `pred`. Visits members in increasing order and stops at the first that satisfies it. - **cost**: O(K / 64 + visited) words scanned and calls of `pred` - **empty**: `false` - **traps**: never (beyond what `pred` traps on) Examples: - `domain D = 0..10; Bitset.of([D(1), D(3), D(8)]).any(d => Int(d) > 5)` - `domain D = 0..10; not Bitset().any(d => true)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L165) ### `Bitset.len` ```cp fn len(self) -> Int ``` The number of positions in the set; the count is kept current by every update. - **cost**: O(1) - **traps**: never Examples: - `domain D = 0..10; Bitset.of([D(1), D(3), D(8)]).len == 3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L171) ### `Bitset.count` ```cp fn count(self) -> Int ``` The same number as `len`, under the name C++ gives it. - **cost**: O(1) - **traps**: never Examples: - `domain D = 0..10; Bitset.of([D(1), D(3), D(8)]).count == 3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L178) ### `Bitset.is_empty` ```cp fn is_empty(self) -> Bool ``` Whether the set has no members. O(1): the count is kept current by every update. - **cost**: O(1) - **traps**: never Examples: - `domain D = 0..10; Bitset().is_empty and not Bitset.full().is_empty` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L185) ### `Bitset.first` ```cp fn first(self) -> ?D ``` The smallest position in the set, or `None`. - **cost**: O(K / 64) - **empty**: `None` - **ties**: None possible; positions are distinct - **traps**: never Examples: - `domain D = 0..10; Bitset.of([D(1), D(3), D(8)]).first() == Some(D(1))` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L194) ### `Bitset.find` ```cp fn find(self, pred: D -> Bool) -> ?D ``` The smallest position in the set satisfying `pred`, or `None`, as `seq.find`. Members are visited in increasing order, so `pred` is called only up to the answer. - **cost**: O(K / 64 + visited) - **empty**: `None` - **ties**: None possible; the smallest qualifying position wins - **traps**: never (beyond what `pred` traps on) Examples: - `domain D = 0..10; Bitset.of([D(1), D(3), D(8)]).find(d => Int(d) > 2) == Some(D(3))` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L204) ### `Bitset.rfind` ```cp fn rfind(self, pred: D -> Bool) -> ?D ``` The largest position in the set satisfying `pred`, or `None`. Members are visited in decreasing order. - **cost**: O(K / 64 + visited) - **empty**: `None` - **ties**: None possible; the largest qualifying position wins - **traps**: never (beyond what `pred` traps on) Examples: - `domain D = 0..10; Bitset.of([D(1), D(3), D(8)]).rfind(d => Int(d) < 8) == Some(D(3))` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L222) ### `Bitset.union` ```cp fn union(mut self, o: Bitset) ``` Replace `self` with `self | o` in place, with no allocation. - **cost**: O(K / 64) - **traps**: never Examples: - `domain D = 0..10; var b = Bitset.single(D(1)); b.union(Bitset.single(D(2))); b.len == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L232) ### `Bitset.intersect` ```cp fn intersect(mut self, o: Bitset) ``` Replace `self` with `self & o` in place, with no allocation. - **cost**: O(K / 64) - **traps**: never Examples: - `domain D = 0..10; var b = Bitset.of([D(1), D(2)]); b.intersect(Bitset.single(D(2))); b.each().collect() == [D(2)]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L241) ### `Bitset.subtract` ```cp fn subtract(mut self, o: Bitset) ``` Clear every bit set in `o` from `self` in place: `self - o`. - **cost**: O(K / 64) - **traps**: never Examples: - `domain D = 0..10; var b = Bitset.of([D(1), D(2)]); b.subtract(Bitset.single(D(2))); b.each().collect() == [D(1)]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L250) ### `Bitset.symmetric` ```cp fn symmetric(mut self, o: Bitset) ``` Replace `self` with `self ^ o` in place. - **cost**: O(K / 64) - **traps**: never Examples: - `domain D = 0..10; var b = Bitset.of([D(1), D(2)]); b.symmetric(Bitset.of([D(2), D(3)])); b.each().collect() == [D(1), D(3)]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L259) ### `Bitset.bitor` ```cp fn bitor(self, o: Bitset) -> Bitset ``` `a | b`: a new set of the positions in either set. - **cost**: O(K / 64) time and space - **traps**: never Examples: - `domain D = 0..10; (Bitset.single(D(1)) | Bitset.single(D(2))).len == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L268) ### `Bitset.bitand` ```cp fn bitand(self, o: Bitset) -> Bitset ``` `a & b`: a new set of the positions in both sets. - **cost**: O(K / 64) time and space - **traps**: never Examples: - `domain D = 0..10; (Bitset.of([D(1), D(2)]) & Bitset.of([D(2), D(3)])).each().collect() == [D(2)]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L279) ### `Bitset.bitxor` ```cp fn bitxor(self, o: Bitset) -> Bitset ``` `a ^ b`: a new set of the positions in exactly one of the sets. - **cost**: O(K / 64) time and space - **traps**: never Examples: - `domain D = 0..10; (Bitset.of([D(1), D(2)]) ^ Bitset.of([D(2), D(3)])).each().collect() == [D(1), D(3)]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L290) ### `Bitset.meets` ```cp fn meets(self, o: Bitset) -> Bool ``` Do the two sets share a position? Stops at the first shared word; `(a & b).len > 0` without building `a & b`. - **cost**: O(K / 64), less on an early hit - **traps**: never Examples: - `domain D = 0..10; Bitset.of([D(1), D(2)]).meets(Bitset.of([D(2), D(3)]))` - `domain D = 0..10; not Bitset.single(D(1)).meets(Bitset.single(D(2)))` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L303) ### `Bitset.shifted` ```cp fn shifted(self, k: Int) -> Bitset ``` A new set with every position `k` places up (down for a negative `k`); positions that leave `D` are dropped. Position `v` moves to the position whose ordinal is `v`'s plus `k`. - **cost**: O(K / 64) time and space, for any `k` - **traps**: never Examples: - `domain D = 0..10; Bitset.of([D(1), D(3), D(8)]).shifted(2).each().collect() == [D(3), D(5)]` - `domain D = 0..10; Bitset.of([D(1), D(3), D(8)]).shifted(-2).each().collect() == [D(1), D(6)]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L315) ### `Bitset.shift_up` ```cp fn shift_up(mut self, k: Int) ``` Shift every position `k >= 0` places up in place; bits past `D` drop. - **cost**: O(K / 64) - **traps**: when `k < 0` Examples: - `domain D = 0..10; var b = Bitset.of([D(1), D(3), D(8)]); b.shift_up(1); b.each().collect() == [D(2), D(4), D(9)]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L342) ### `Bitset.shift_or` ```cp fn shift_or(mut self, k: Int) ``` In-place `self |= self << k` for `k >= 0`, with zero allocation: the knapsack step "every reachable sum, and every reachable sum plus `k`". Bits past `D` drop. - **cost**: O(K / 64) - **traps**: when `k < 0` Examples: - `domain D = 0..10; var b = Bitset.of([D(1), D(3), D(8)]); b.shift_or(2); b.each().collect() == [D(1), D(3), D(5), D(8)]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L363) ### `Bitset.each` ```cp fn each(self) -> yields D ``` The positions in the set, in increasing order; `for v in b` walks the same sequence. - **cost**: O(K / 64 + len) to walk, O(1) per member amortized - **empty**: yields nothing - **order**: increasing - **traps**: never Examples: - `domain D = 0..10; Bitset.of([D(8), D(1)]).each().collect() == [D(1), D(8)]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L382) ### `Bitset.next` ```cp fn next(self, i: D) -> ?D ``` The first position in the set at or after `i`, or `None`. - **cost**: O(K / 64) - **empty**: `None` - **traps**: never Examples: - `domain D = 0..10; Bitset.of([D(1), D(3), D(8)]).next(D(3)) == Some(D(3))` - `domain D = 0..10; Bitset.of([D(1), D(3), D(8)]).next(D(4)) == Some(D(8))` - `domain D = 0..10; Bitset.of([D(1), D(3), D(8)]).next(D(9)) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L398) ### `Bitset.prev` ```cp fn prev(self, i: D) -> ?D ``` The last position in the set at or before `i`, or `None` (the mirror of `next`). - **cost**: O(K / 64) - **empty**: `None` - **traps**: never Examples: - `domain D = 0..10; Bitset.of([D(1), D(3), D(8)]).prev(D(3)) == Some(D(3))` - `domain D = 0..10; Bitset.of([D(1), D(3), D(8)]).prev(D(2)) == Some(D(1))` - `domain D = 0..10; Bitset.of([D(1), D(3), D(8)]).prev(D(0)) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L415) ### `Bitset.count_below` ```cp fn count_below(self, i: D) -> Int ``` The number of positions in the set strictly before `i`. - **cost**: O(K / 64) - **empty**: zero - **traps**: never Examples: - `domain D = 0..10; Bitset.of([D(1), D(3), D(8)]).count_below(D(8)) == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L432) ### `Bitset.subset_sums` ```cp fn subset_sums(weights: List) -> Bitset ``` All subset sums in `0..D.K` reachable from non-negative `weights`: the position with ordinal `s` is set exactly when some sub-multiset of `weights` sums to `s`. The empty sub-multiset makes `0` reachable; sums of `D.K` or more are dropped. Groups duplicate weights with binary carries so the work is O(K sqrt(S) / 64). - **cost**: O(K sqrt(S) / 64) time, where S is the sum of `weights`; O(K / 64) space - **empty**: `{D.first}` (just the sum 0), or the empty set when `D` is empty - **traps**: when a weight is negative Examples: - `domain S = 0..=10; Bitset.subset_sums([3, 5, 5]).each().map(s => Int(s)).collect() == [0, 3, 5, 8, 10]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L449) ### `Bitset.shift_down` ```cp fn shift_down(mut self, k: Int) ``` Shift all bits down by `k >= 0` positions in place (`i -> i - k`); bits below `D` drop. - **cost**: O(K / 64) - **traps**: when `k < 0` Examples: - `domain D = 0..10; var b = Bitset.of([D(1), D(3), D(8)]); b.shift_down(1); b.each().collect() == [D(0), D(2), D(7)]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L470) ### `Bitset.count_range` ```cp fn count_range(self, r: Range) -> Int ``` Count set bits in `r` (accepts cut ranges via decision 124). - **cost**: O(r.len / 64 + 1) - **empty**: zero - **traps**: never Examples: - `domain D = 0..10; Bitset.of([D(1), D(3), D(8)]).count_range(1..8) == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L482) ### `Bitset.set_range` ```cp fn set_range(mut self, r: Range, on: Bool = true) ``` Set (or, with `on: false`, clear) every bit in `r` in place. - **cost**: O(r.len / 64 + 1) - **empty**: no effect - **traps**: never Examples: - `domain D = 0..10; var b = Bitset.of([D(1), D(3), D(8)]); b.set_range(2..5); b.len == 5` - `domain D = 0..10; var b = Bitset.of([D(1), D(3), D(8)]); b.set_range(0..4, on: false); b.each().collect() == [D(8)]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L496) ### `Bitset.flip_range` ```cp fn flip_range(mut self, r: Range) ``` Flip every bit in `r` in place. - **cost**: O(r.len / 64 + 1) - **empty**: no effect - **traps**: never Examples: - `domain D = 0..10; var b = Bitset.of([D(1), D(3), D(8)]); b.flip_range(0..4); b.each().collect() == [D(0), D(2), D(8)]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L511) ### `Bitset.nth` ```cp fn nth(self, k: Int) -> ?D ``` The `k`-th set position (0-based, in increasing order), or `None` if `k >= len`. - **cost**: O(K / 64) - **empty**: `None` - **traps**: when `k < 0` Examples: - `domain D = 0..10; Bitset.of([D(1), D(3), D(8)]).nth(2) == Some(D(8))` - `domain D = 0..10; Bitset.of([D(1), D(3), D(8)]).nth(3) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L527) ### `Bitset.each_rev` ```cp fn each_rev(self) -> yields D ``` The set positions in descending order. - **cost**: O(K / 64 + len) to walk - **empty**: yields nothing - **order**: decreasing - **traps**: never Examples: - `domain D = 0..10; Bitset.of([D(1), D(3), D(8)]).each_rev().collect() == [D(8), D(3), D(1)]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L546) ### `Bitset.recount` ```cp fn recount(mut self) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L554) ### `Bitset.trim` ```cp fn trim(mut self) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L558) ## `DynBitset` ```cp pub struct DynBitset ``` Runtime-sized 64-bit word bitset over `0..cap` when the width is computed dynamically without a domain. Single-bit ops are O(1); word-parallel ops are O(cap / 64). [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L566) ### `DynBitset.recount` ```cp fn recount(mut self) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L571) ### `DynBitset.trim` ```cp fn trim(mut self) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L575) ### `DynBitset.new` ```cp fn new(cap: Int) -> DynBitset ``` Create an all-zero `DynBitset` of width `cap`: bits `0..cap`. - **cost**: O(cap / 64) time and space - **traps**: when `cap < 0` Examples: - `DynBitset(10).len == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L584) ### `DynBitset.full` ```cp fn full(cap: Int) -> DynBitset ``` Create an all-one `DynBitset` of width `cap`; bits at or above `cap` stay clear. - **cost**: O(cap / 64) time and space - **traps**: when `cap < 0` Examples: - `DynBitset.full(10).len == 10` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L593) ### `DynBitset.cap` ```cp fn cap(self) -> Int ``` The bit capacity: valid indices are `0..cap`. - **cost**: O(1) - **traps**: never Examples: - `DynBitset(10).cap == 10` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L604) ### `DynBitset.len` ```cp fn len(self) -> Int ``` The number of set bits, kept current by every update. - **cost**: O(1) - **traps**: never Examples: - `var d = DynBitset(10); d.add(1); d.add(3); d.len == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L611) ### `DynBitset.is_empty` ```cp fn is_empty(self) -> Bool ``` Whether no bits are set, kept current by every update. - **cost**: O(1) - **traps**: never Examples: - `DynBitset(10).is_empty and not DynBitset.full(1).is_empty` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L618) ### `DynBitset.contains` ```cp fn contains(self, i: Int) -> Bool ``` Whether bit `i` is set. - **cost**: O(1) - **traps**: when `i` is not in `0..cap` Examples: - `var d = DynBitset(10); d.add(3); d.contains(3) and not d.contains(4)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L625) ### `DynBitset.set` ```cp fn set(mut self, i: Int, on: Bool = true) ``` Set bit `i` to `on` in place (W8 `IndexSet` backing `b[i] = on`). - **cost**: O(1) - **traps**: when `i` is not in `0..cap` Examples: - `var d = DynBitset(10); d.set(4); d.set(5, true); d.set(4, false); d.each().collect() == [5]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L634) ### `DynBitset.add` ```cp fn add(mut self, i: Int) -> Bool ``` Set bit `i` to 1; returns `true` if bit `i` was previously 0 (matches `Bitset.add`). - **cost**: O(1) - **traps**: when `i` is not in `0..cap` Examples: - `var d = DynBitset(10); let x = d.add(2); let y = d.add(2); x and not y` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L642) ### `DynBitset.remove` ```cp fn remove(mut self, i: Int) -> Bool ``` Clear bit `i` to 0; returns `true` if bit `i` was previously 1 (matches `Bitset.remove`). - **cost**: O(1) - **traps**: when `i` is not in `0..cap` Examples: - `var d = DynBitset(10); d.add(2); let x = d.remove(2); let y = d.remove(2); x and not y and d.is_empty` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L653) ### `DynBitset.toggle` ```cp fn toggle(mut self, i: Int) ``` Flip bit `i`. - **cost**: O(1) - **traps**: when `i` is not in `0..cap` Examples: - `var d = DynBitset(10); d.toggle(6); d.toggle(6); d.toggle(7); d.each().collect() == [7]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L664) ### `DynBitset.clear` ```cp fn clear(mut self) ``` Clear all bits; the capacity is unchanged. - **cost**: O(cap / 64) - **traps**: never Examples: - `var d = DynBitset.full(10); d.clear(); d.is_empty and d.cap == 10` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L673) ### `DynBitset.resize` ```cp fn resize(mut self, new_cap: Int) ``` Resize to `new_cap` bits, zero-filling any new high bits. Shrinking drops the bits at or above `new_cap` (and `len` drops with them). - **cost**: O(new_cap / 64) time and space - **traps**: when `new_cap < 0` Examples: - `var d = DynBitset(10); d.add(1); d.add(8); d.resize(4); d.len == 1 and d.cap == 4` - `var d = DynBitset.full(2); d.resize(5); d.each().collect() == [0, 1]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L684) ### `DynBitset.first` ```cp fn first(self) -> ?Int ``` The smallest set bit index, or `None` if empty. - **cost**: O(cap / 64) - **empty**: `None` - **ties**: None possible; the smallest index wins - **traps**: never Examples: - `var d = DynBitset(10); d.add(8); d.add(3); d.first() == Some(3)` - `DynBitset(10).first() == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L701) ### `DynBitset.last` ```cp fn last(self) -> ?Int ``` The largest set bit index, or `None` if empty. - **cost**: O(cap / 64) - **empty**: `None` - **ties**: None possible; the largest index wins - **traps**: never Examples: - `var d = DynBitset(10); d.add(8); d.add(3); d.last() == Some(8)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L710) ### `DynBitset.next` ```cp fn next(self, i: Int) -> ?Int ``` The smallest set bit `>= i`, or `None`. - **cost**: O(cap / 64) - **empty**: `None` - **traps**: when `i` is not in `0..=cap` Examples: - `var d = DynBitset(10); d.add(3); d.add(8); d.next(3) == Some(3) and d.next(4) == Some(8) and d.next(9) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L720) ### `DynBitset.prev` ```cp fn prev(self, i: Int) -> ?Int ``` The largest set bit `<= i`, or `None`; `i` itself counts, as in `Bitset.prev`. - **cost**: O(cap / 64) - **empty**: `None` - **traps**: when `i` is not in `0..cap` Examples: - `var d = DynBitset(10); d.add(1); d.add(3); d.prev(3) == Some(3) and d.prev(2) == Some(1) and d.prev(0) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L738) ### `DynBitset.count_below` ```cp fn count_below(self, i: Int) -> Int ``` The number of set bits strictly below `i`. - **cost**: O(cap / 64) - **empty**: zero - **traps**: when `i` is not in `0..=cap` Examples: - `var d = DynBitset(10); d.add(1); d.add(3); d.add(8); d.count_below(8) == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L755) ### `DynBitset.count_range` ```cp fn count_range(self, r: Range) -> Int ``` The number of set bits in `r`. - **cost**: O(r.len / 64 + 1) - **empty**: zero - **traps**: when `r` is non-empty and reaches outside `0..cap` Examples: - `var d = DynBitset(10); d.add(1); d.add(3); d.add(8); d.count_range(1..8) == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L765) ### `DynBitset.nth` ```cp fn nth(self, k: Int) -> ?Int ``` The `k`-th set bit index (0-based, in increasing order), or `None` if `k >= len`. - **cost**: O(cap / 64) - **empty**: `None` - **traps**: when `k < 0` Examples: - `var d = DynBitset(10); d.add(1); d.add(3); d.add(8); d.nth(1) == Some(3) and d.nth(3) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L779) ### `DynBitset.union` ```cp fn union(mut self, other: DynBitset) ``` In-place bitwise OR (`self |= other`). - **cost**: O(cap / 64) - **traps**: when `other.cap != self.cap` Examples: - `var a = DynBitset(4); a.add(0); var b = DynBitset(4); b.add(2); a.union(b); a.each().collect() == [0, 2]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L796) ### `DynBitset.intersect` ```cp fn intersect(mut self, other: DynBitset) ``` In-place bitwise AND (`self &= other`). - **cost**: O(cap / 64) - **traps**: when `other.cap != self.cap` Examples: - `var a = DynBitset.full(4); var b = DynBitset(4); b.add(2); a.intersect(b); a.each().collect() == [2]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L806) ### `DynBitset.subtract` ```cp fn subtract(mut self, other: DynBitset) ``` In-place set difference (`self &= ~other`). - **cost**: O(cap / 64) - **traps**: when `other.cap != self.cap` Examples: - `var a = DynBitset.full(4); var b = DynBitset(4); b.add(2); a.subtract(b); a.each().collect() == [0, 1, 3]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L816) ### `DynBitset.symmetric` ```cp fn symmetric(mut self, other: DynBitset) ``` In-place bitwise XOR (`self ^= other`). - **cost**: O(cap / 64) - **traps**: when `other.cap != self.cap` Examples: - `var a = DynBitset(4); a.add(1); a.add(2); var b = DynBitset(4); b.add(2); b.add(3); a.symmetric(b); a.each().collect() == [1, 3]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L826) ### `DynBitset.meets` ```cp fn meets(self, other: DynBitset) -> Bool ``` Whether `self` and `other` share a set bit; stops at the first shared word. - **cost**: O(cap / 64), less on an early hit - **traps**: when `other.cap != self.cap` Examples: - `var a = DynBitset(4); a.add(1); var b = DynBitset.full(4); a.meets(b) and not a.meets(DynBitset(4))` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L836) ### `DynBitset.shift_up` ```cp fn shift_up(mut self, k: Int) ``` Shift all bits up by `k >= 0` in place (`i -> i + k`); bits reaching `cap` or beyond drop. - **cost**: O(cap / 64) - **traps**: when `k < 0` Examples: - `var d = DynBitset(10); d.add(1); d.add(3); d.add(8); d.shift_up(2); d.each().collect() == [3, 5]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L847) ### `DynBitset.shift_down` ```cp fn shift_down(mut self, k: Int) ``` Shift all bits down by `k >= 0` in place (`i -> i - k`); bits falling below 0 drop. - **cost**: O(cap / 64) - **traps**: when `k < 0` Examples: - `var d = DynBitset(10); d.add(1); d.add(3); d.add(8); d.shift_down(2); d.each().collect() == [1, 6]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L865) ### `DynBitset.shift_or` ```cp fn shift_or(mut self, k: Int) ``` In-place `self |= (self << k)` for `k >= 0`, with zero allocation; bits reaching `cap` drop. - **cost**: O(cap / 64) - **traps**: when `k < 0` Examples: - `var d = DynBitset(10); d.add(1); d.add(3); d.add(8); d.shift_or(2); d.each().collect() == [1, 3, 5, 8]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L882) ### `DynBitset.each` ```cp fn each(self) -> yields Int ``` The set bit indices in ascending order; `for i in d` walks the same sequence. - **cost**: O(cap / 64 + len) to walk - **empty**: yields nothing - **order**: increasing - **traps**: never Examples: - `var d = DynBitset(10); d.add(8); d.add(1); d.each().collect() == [1, 8]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L902) ### `DynBitset.each_rev` ```cp fn each_rev(self) -> yields Int ``` The set bit indices in descending order. - **cost**: O(cap / 64 + len) to walk - **empty**: yields nothing - **order**: decreasing - **traps**: never Examples: - `var d = DynBitset(10); d.add(8); d.add(1); d.each_rev().collect() == [8, 1]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L917) ### `DynBitset.subset_sums` ```cp fn subset_sums(cap: Int, weights: List) -> DynBitset ``` All subset sums in `0..cap` reachable from `weights`: bit `s` is set exactly when some sub-multiset of `weights` sums to `s`. The empty sub-multiset makes `0` reachable (when `cap > 0`); sums of `cap` or more drop. Duplicate weights are grouped with binary carries, as in `Bitset.subset_sums`. - **cost**: O(cap sqrt(S) / 64) time, where S is the sum of `weights`; O(cap / 64) space - **empty**: just bit 0 (None when `cap == 0`) - **traps**: when `cap < 0` or a weight is negative Examples: - `DynBitset.subset_sums(11, [3, 5, 5]).each().collect() == [0, 3, 5, 8, 10]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L934) ## `XorTrie` ```cp pub struct XorTrie ``` O(bits) per op. Dynamic binary bitwise XOR trie multiset over non-negative `bits`-bit integers (default 60 bits). [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L951) ### `XorTrie.child` ```cp fn child(self, node: Int, b: Int) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L959) ### `XorTrie.leaf` ```cp fn leaf(self, x: Int) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L961) ### `XorTrie.walk` ```cp fn walk(mut self, x: Int, d: Int, dd: Int) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L969) ### `XorTrie.new` ```cp fn new(bits: Int = 60) -> XorTrie ``` Create an empty `XorTrie` over `bits`-bit non-negative integers (default 60): values in `0..2^bits`. - **cost**: O(1) - **traps**: when `bits` is not in `1..=62` Examples: - `XorTrie(3).is_empty` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L994) ### `XorTrie.reserve` ```cp fn reserve(mut self, nodes: Int) ``` Reserve pool capacity for at least `nodes` trie nodes, so later adds do not reallocate; the contents are unchanged. - **cost**: O(nodes) time and space - **traps**: when `nodes < 0` Examples: - `var t = XorTrie(3); t.reserve(100); t.len == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L1004) ### `XorTrie.len` ```cp fn len(self) -> Int ``` The total number of stored integers, with multiplicity. - **cost**: O(1) - **traps**: never Examples: - `var t = XorTrie(3); t.add(5); t.add(5); t.len == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L1012) ### `XorTrie.is_empty` ```cp fn is_empty(self) -> Bool ``` True when the trie holds no integers. - **cost**: O(1) - **traps**: never Examples: - `var t = XorTrie(3); t.add(5); t.remove(5); t.is_empty` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L1019) ### `XorTrie.add` ```cp fn add(mut self, x: Int) ``` Insert one copy of `x`. `x` is stored as given, after any earlier `xor_all`: the mask applies only to elements already present. - **cost**: O(bits) time, up to `bits` new nodes - **traps**: when `x` is not in `0..2^bits` Examples: - `var t = XorTrie(3); t.add(5); t.add(5); t.count(5) == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L1027) ### `XorTrie.remove` ```cp fn remove(mut self, x: Int) -> Bool ``` Remove one copy of `x`; returns `false` if absent, leaving the trie unchanged. - **cost**: O(bits) - **traps**: never Examples: - `var t = XorTrie(3); t.add(5); let x = t.remove(5); let y = t.remove(5); x and not y` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L1036) ### `XorTrie.contains` ```cp fn contains(self, x: Int) -> Bool ``` Whether `x` is present at least once. - **cost**: O(bits) - **traps**: never Examples: - `var t = XorTrie(3); t.add(5); t.contains(5) and not t.contains(4)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L1047) ### `XorTrie.count` ```cp fn count(self, x: Int) -> Int ``` The multiplicity of `x` currently stored; zero when absent. - **cost**: O(bits) - **traps**: never Examples: - `var t = XorTrie(3); t.add(5); t.add(5); t.add(1); t.count(5) == 2 and t.count(2) == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L1054) ### `XorTrie.xor_all` ```cp fn xor_all(mut self, mask: Int) ``` Apply a lazy global XOR mask: every stored `y` becomes `y ^ mask`. Masks compose (`xor_all(a)` then `xor_all(b)` is `xor_all(a ^ b)`). - **cost**: O(1) - **traps**: when `mask` is not in `0..2^bits` Examples: - `var t = XorTrie(3); t.add(1); t.add(5); t.xor_all(1); t.contains(0) and t.contains(4) and not t.contains(1)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L1065) ### `XorTrie.max_xor` ```cp fn max_xor(self, x: Int) -> ?Int ``` The maximum value of `x ^ y` over stored `y`, or `None` if empty. - **cost**: O(bits) - **empty**: `None` - **ties**: None possible; the value is unique even when several `y` reach it - **traps**: when `x` is not in `0..2^bits` Examples: - `var t = XorTrie(3); t.add(1); t.add(5); t.add(6); t.max_xor(2) == Some(7)` - `XorTrie(3).max_xor(2) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L1077) ### `XorTrie.min_xor` ```cp fn min_xor(self, x: Int) -> ?Int ``` The minimum value of `x ^ y` over stored `y`, or `None` if empty. - **cost**: O(bits) - **empty**: `None` - **ties**: None possible; the value is unique even when several `y` reach it - **traps**: when `x` is not in `0..2^bits` Examples: - `var t = XorTrie(3); t.add(1); t.add(5); t.add(6); t.min_xor(2) == Some(3)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L1086) ### `XorTrie.count_xor_less` ```cp fn count_xor_less(self, x: Int, limit: Int) -> Int ``` The number of stored `y` (with multiplicity) with `(x ^ y) < limit`. A `limit <= 0` gives 0 and a `limit >= 2^bits` gives `len`. - **cost**: O(bits) - **traps**: when `x` is not in `0..2^bits` Examples: - `var t = XorTrie(3); t.add(1); t.add(5); t.add(6); t.count_xor_less(2, 5) == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L1094) ### `XorTrie.kth_xor` ```cp fn kth_xor(self, x: Int, k: Int) -> ?Int ``` The `k`-th smallest value of `x ^ y` over stored `y` (0-based, with multiplicity), or `None` if `k >= len`. - **cost**: O(bits) - **empty**: `None` - **ties**: equal values `x ^ y` (copies of one `y`) each take their own rank - **traps**: when `k < 0` or `x` is not in `0..2^bits` Examples: - `var t = XorTrie(3); t.add(1); t.add(5); t.add(6); t.kth_xor(2, 1) == Some(4)` - `var t = XorTrie(3); t.add(1); t.add(5); t.add(6); t.kth_xor(2, 3) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L1121) ### `XorTrie.mex_xor` ```cp fn mex_xor(self, x: Int = 0) -> Int ``` The smallest non-negative integer not present under XOR mask `x` (mex of `{y ^ x}`); `2^bits` when every value is present. - **cost**: O(bits) - **empty**: zero - **traps**: when `x` is not in `0..2^bits` Examples: - `var t = XorTrie(3); t.add(1); t.add(5); t.add(6); t.mex_xor() == 0 and t.mex_xor(1) == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L1147) ### `XorTrie.extreme_xor` ```cp fn extreme_xor(self, x: Int, want: Int) -> ?Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L1163) ### `XorTrie.clear` ```cp fn clear(mut self) ``` Remove all elements and the global mask, keeping `bits` and the reserved pool. - **cost**: O(1) - **traps**: never Examples: - `var t = XorTrie(3); t.add(5); t.clear(); t.is_empty and not t.contains(5)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L1185) ## `Bitset` ```cp impl Sub for Bitset ``` `a - b`: the positions in `a` that are not in `b`. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L1193) ### `Bitset.sub` ```cp fn sub(a, b) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L1194) ## `Bitset` ```cp impl Show for Bitset ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L1202) ### `Bitset.show` ```cp fn show(a) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/bitset.cp#L1203) --- # deque URL: /docs/ref/std/deque Generated from [spec/std/deque.cp](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/deque.cp) by `cpl doc --format json`. ## `Deque` ```cp pub struct Deque ``` A queue with both ends open: `var q = Deque()`. `push` / `pop` work at the back, `push_front` / `pop_front` at the front, all amortized O(1); `q[i]` is the `i`-th element from the front in O(1). Memory is a ring of at most twice the largest length. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/deque.cp#L8) ### `Deque.new` ```cp fn new() -> Deque ``` Create an empty `Deque`. - **cost**: O(1); nothing is allocated until the first push - **traps**: never Examples: - `var q: Deque = Deque(); q.len == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/deque.cp#L20) ### `Deque.of` ```cp fn of(xs: List) -> Deque ``` A deque holding `xs`, front to back: the queue of a search, `var q = Deque.of(sources)`, then `while let u = q.pop_front(): ...`. O(n). The first element of `xs` is the front, so `pop_front` returns the elements in the order `xs` lists them. - **cost**: O(n) - **empty**: an empty deque - **traps**: never Examples: - `Deque.of([1, 2, 3]).to_list() == [1, 2, 3]` - `var q = Deque.of([1, 2]); q.pop_front() == Some(1)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/deque.cp#L33) ### `Deque.reserve` ```cp fn reserve(mut self, cap: Int) ``` Reserve capacity for at least `cap` elements without reallocating. O(1) when empty, O(cap) otherwise. The contents and their order do not change; a `cap` no larger than the current capacity (including any `cap <= 0`) does nothing. - **cost**: O(1) when empty, O(cap) otherwise - **traps**: never Examples: - `var q = Deque.of([1, 2]); q.reserve(100); q.to_list() == [1, 2]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/deque.cp#L47) ### `Deque.len` ```cp fn len(self) -> Int ``` Number of elements currently in the deque. - **cost**: O(1) - **traps**: never Examples: - `Deque.of([4, 5]).len == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/deque.cp#L61) ### `Deque.is_empty` ```cp fn is_empty(self) -> Bool ``` Whether the deque is empty. - **cost**: O(1) - **traps**: never Examples: - `Deque.of([7]).is_empty == false` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/deque.cp#L68) ### `Deque.clear` ```cp fn clear(mut self) ``` Remove all elements from the deque. The capacity is kept, so refilling does not reallocate. - **cost**: O(1) - **traps**: never Examples: - `var q = Deque.of([1, 2]); q.clear(); q.len == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/deque.cp#L78) ### `Deque.take` ```cp fn take(mut self) -> Deque ``` Move the deque's contents out in O(1), leaving `self` empty. - **cost**: O(1) - **traps**: never Examples: - `var q = Deque.of([1, 2]); let r = q.take(); q.len == 0 and r.to_list() == [1, 2]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/deque.cp#L90) ### `Deque.grow_to` ```cp fn grow_to(mut self, cap: Int, fill: T) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/deque.cp#L99) ### `Deque.push` ```cp fn push(mut self, x: T) ``` Append `x` to the back of the deque. - **cost**: O(1) amortized; a full ring doubles - **traps**: never Examples: - `var q = Deque.of([1]); q.push(2); q.to_list() == [1, 2]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/deque.cp#L114) ### `Deque.push_front` ```cp fn push_front(mut self, x: T) ``` Prepend `x` to the front of the deque. Every existing element moves one place back: `q[0]` is now `x`. - **cost**: O(1) amortized; a full ring doubles - **traps**: never Examples: - `var q = Deque.of([1]); q.push_front(0); q.to_list() == [0, 1]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/deque.cp#L129) ### `Deque.pop` ```cp fn pop(mut self) -> ?T ``` Remove and return the back, or `None` when empty. - **cost**: O(1) - **empty**: `None`, and the deque stays empty - **traps**: never Examples: - `var q = Deque.of([1, 2]); q.pop() == Some(2) and q.to_list() == [1]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/deque.cp#L144) ### `Deque.pop_front` ```cp fn pop_front(mut self) -> ?T ``` Remove and return the front, or `None` when empty. - **cost**: O(1) - **empty**: `None`, and the deque stays empty - **traps**: never Examples: - `var q = Deque.of([1, 2]); q.pop_front() == Some(1) and q.to_list() == [2]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/deque.cp#L156) ### `Deque.pop_front_while` ```cp fn pop_front_while(mut self, ok: T -> Bool) -> List ``` O(k) for `k` removed. Remove and return the longest front run on which `ok` holds, in order: a queue sorted by key releases everything below a rising threshold. `ok` is called front to back and the run stops at the first element where it is false; that element and everything behind it stay. `ok` is called at most `k + 1` times. - **cost**: O(k) for `k` removed - **empty**: `[]` - **order**: front first, the order the elements sat in; a new `List`, keyed from 0 - **traps**: never Examples: - `var q = Deque.of([1, 2, 5, 3]); q.pop_front_while(x => x < 4) == [1, 2] and q.to_list() == [5, 3]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/deque.cp#L175) ### `Deque.pop_while` ```cp fn pop_while(mut self, ok: T -> Bool) -> List ``` Pop from the back while `ok` holds; the popped values, back first. O(popped). The mirror of `pop_front_while`: `ok` is called back to front and the run stops at the first element where it is false. - **cost**: O(k) for `k` removed - **empty**: `[]` - **order**: back first, the order they were popped; a new `List`, keyed from 0 - **traps**: never Examples: - `var q = Deque.of([5, 1, 2]); q.pop_while(x => x < 4) == [2, 1] and q.to_list() == [5]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/deque.cp#L191) ### `Deque.first` ```cp fn first(self) -> ?T ``` The front, or `None` when empty. - **cost**: O(1) - **empty**: `None` - **ties**: none: there is one front - **traps**: never Examples: - `Deque.of([4, 5]).first == Some(4)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/deque.cp#L203) ### `Deque.last` ```cp fn last(self, k: Int = 0) -> ?T ``` The back, or `None` when empty. `dq.last(k)` is the element `k` back from it, so `dq.last(1)` is the one before the back. `dq.last(k)` is `dq[dq.len - 1 - k]` when `k < dq.len`, and `None` otherwise. - **cost**: O(1) - **empty**: `None` for every `k` - **ties**: none: each `k` names one place - **traps**: when `k < 0` Examples: - `Deque.of([4, 5, 6]).last == Some(6)` - `Deque.of([4, 5, 6]).last(1) == Some(5)` - `Deque.of([4]).last(1) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/deque.cp#L219) ### `Deque.items` ```cp fn items(self) -> yields (Int, T) ``` Each element with its place from the front: `for (i, x) in dq.items`. O(1) to make, O(n) to walk. - **cost**: O(1) to make, O(1) per step - **empty**: yields nothing - **order**: front to back; the places are `0..len` - **traps**: never Examples: - `Deque.of([7, 8]).items.collect() == [(0, 7), (1, 8)]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/deque.cp#L231) ### `Deque.get` ```cp fn get(self, i: Int) -> T ``` The `i`-th element from the front. `q[i]` calls this; place `0` is the front and `len - 1` the back. - **cost**: O(1) - **traps**: when `i` is not in `0..len` Examples: - `Deque.of([7, 8]).get(1) == 8` - `var q = Deque.of([1]); q.push_front(0); q[0] == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/deque.cp#L242) ### `Deque.set` ```cp fn set(mut self, i: Int, x: T) ``` Overwrite the `i`-th element from the front (W8 `IndexSet` backing `dq[i] = x`). - **cost**: O(1) - **traps**: when `i` is not in `0..len` Examples: - `var q = Deque.of([7, 8]); q[0] = 9; q.to_list() == [9, 8]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/deque.cp#L252) ### `Deque.to_list` ```cp fn to_list(self) -> List ``` Materialize the elements front to back as a `List`. - **cost**: O(n), one new `List` - **empty**: `[]` - **order**: front to back; a new `List`, keyed from 0 - **traps**: never Examples: - `var q = Deque.of([2]); q.push_front(1); q.to_list() == [1, 2]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/deque.cp#L264) ### `Deque.each` ```cp fn each(self) -> yields T ``` Yield elements front to back without allocating. `for x in q` uses this. - **cost**: O(1) per step - **empty**: yields nothing - **order**: front to back - **traps**: never Examples: - `Deque.of([1, 2]).each().collect() == [1, 2]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/deque.cp#L278) ### `Deque.each_rev` ```cp fn each_rev(self) -> yields T ``` Yield elements back to front without allocating. - **cost**: O(1) per step - **empty**: yields nothing - **order**: back to front - **traps**: never Examples: - `Deque.of([1, 2]).each_rev().collect() == [2, 1]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/deque.cp#L288) ### `Deque.rotate_left` ```cp fn rotate_left(mut self, k: Int) ``` Rotate elements left by `k` positions (`k` mod `len`). The element at place `k` becomes the front. `k` is reduced with Euclidean `%`, so a negative `k` rotates right: `rotate_left(-1)` is `rotate_right(1)`. - **cost**: O(min(k, n - k)) after reducing `k` mod `n` - **empty**: does nothing, for every `k` - **traps**: never Examples: - `var q = Deque.of([1, 2, 3, 4]); q.rotate_left(1); q.to_list() == [2, 3, 4, 1]` - `var q = Deque.of([1, 2, 3, 4]); q.rotate_left(-1); q.to_list() == [4, 1, 2, 3]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/deque.cp#L304) ### `Deque.rotate_right` ```cp fn rotate_right(mut self, k: Int) ``` Rotate elements right by `k` positions (`k` mod `len`). The back `k` elements move to the front, in order. `rotate_right(k)` is `rotate_left(-k)`. - **cost**: O(min(k, n - k)) after reducing `k` mod `n` - **empty**: does nothing, for every `k` - **traps**: never Examples: - `var q = Deque.of([1, 2, 3, 4]); q.rotate_right(1); q.to_list() == [4, 1, 2, 3]` - `var q = Deque.of([1, 2, 3]); q.rotate_right(4); q.to_list() == [3, 1, 2]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/deque.cp#L322) ## `LinkedList` ```cp pub struct LinkedList ``` Doubly-linked list supporting O(1) end pushes/pops and O(1) splicing (`splice_back`, `splice_front`). [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/deque.cp#L327) ### `LinkedList.fwd` ```cp fn fwd(self, i: Int) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/deque.cp#L336) ### `LinkedList.bwd` ```cp fn bwd(self, i: Int) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/deque.cp#L338) ### `LinkedList.set_fwd` ```cp fn set_fwd(mut self, i: Int, j: Int) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/deque.cp#L340) ### `LinkedList.set_bwd` ```cp fn set_bwd(mut self, i: Int, j: Int) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/deque.cp#L343) ### `LinkedList.node` ```cp fn node(mut self, x: T) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/deque.cp#L346) ### `LinkedList.new` ```cp fn new() -> LinkedList ``` Create an empty `LinkedList`. - **cost**: O(1) - **traps**: never Examples: - `var l: LinkedList = LinkedList(); l.len == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/deque.cp#L358) ### `LinkedList.of` ```cp fn of(x: T) -> LinkedList ``` Create a singleton `LinkedList` containing `x`. - **cost**: O(1) - **traps**: never Examples: - `LinkedList.of(5).each().collect() == [5]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/deque.cp#L366) ### `LinkedList.from_list` ```cp fn from_list(xs: List) -> LinkedList ``` Build a `LinkedList` from `xs`, front to back. - **cost**: O(n) - **empty**: an empty list - **traps**: never Examples: - `LinkedList.from_list([1, 2]).each().collect() == [1, 2]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/deque.cp#L377) ### `LinkedList.len` ```cp fn len(self) -> Int ``` Number of elements currently in the list. - **cost**: O(1) - **traps**: never Examples: - `LinkedList.from_list([1, 2, 3]).len == 3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/deque.cp#L387) ### `LinkedList.is_empty` ```cp fn is_empty(self) -> Bool ``` Whether the list is empty. - **cost**: O(1) - **traps**: never Examples: - `LinkedList.of(1).is_empty == false` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/deque.cp#L395) ### `LinkedList.first` ```cp fn first(self) -> ?T ``` The front element, or `None` when the list is empty (as `Deque.first`). - **cost**: O(1) - **empty**: `None` - **ties**: none: there is one front - **traps**: never Examples: - `LinkedList.from_list([1, 2]).first == Some(1)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/deque.cp#L405) ### `LinkedList.last` ```cp fn last(self) -> ?T ``` The back element, or `None` when the list is empty (as `Deque.last`). - **cost**: O(1) - **empty**: `None` - **ties**: none: there is one back - **traps**: never Examples: - `LinkedList.from_list([1, 2]).last == Some(2)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/deque.cp#L415) ### `LinkedList.push` ```cp fn push(mut self, x: T) ``` Append `x` to the back. - **cost**: O(1) - **traps**: never Examples: - `var l = LinkedList.of(1); l.push(2); l.each().collect() == [1, 2]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/deque.cp#L423) ### `LinkedList.push_front` ```cp fn push_front(mut self, x: T) ``` Prepend `x` to the front. - **cost**: O(1) - **traps**: never Examples: - `var l = LinkedList.of(1); l.push_front(0); l.each().collect() == [0, 1]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/deque.cp#L437) ### `LinkedList.pop` ```cp fn pop(mut self) -> ?T ``` Remove and return the back element, or `None` if empty. - **cost**: O(1) - **empty**: `None` - **traps**: never Examples: - `var l = LinkedList.from_list([1, 2]); l.pop() == Some(2) and l.len == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/deque.cp#L452) ### `LinkedList.pop_front` ```cp fn pop_front(mut self) -> ?T ``` Remove and return the front element, or `None` if empty. - **cost**: O(1) - **empty**: `None` - **traps**: never Examples: - `var l = LinkedList.from_list([1, 2]); l.pop_front() == Some(1) and l.first == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/deque.cp#L468) ### `LinkedList.splice_back` ```cp fn splice_back(mut self, other: LinkedList) ``` Splice all elements of `other` onto the back of `self`, consuming `other`. The elements keep their order: `self`'s first, then `other`'s. No element is copied. - **cost**: O(1) - **traps**: never Examples: - `var a = LinkedList.from_list([1, 2]); a.splice_back(LinkedList.from_list([3, 4])); a.each().collect() == [1, 2, 3, 4]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/deque.cp#L484) ### `LinkedList.splice_front` ```cp fn splice_front(mut self, other: LinkedList) ``` Splice all elements of `other` onto the front of `self`, consuming `other`. The elements keep their order: `other`'s first, then `self`'s. - **cost**: O(1) - **traps**: never Examples: - `var a = LinkedList.from_list([1, 2]); a.splice_front(LinkedList.from_list([3, 4])); a.each().collect() == [3, 4, 1, 2]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/deque.cp#L494) ### `LinkedList.reverse` ```cp fn reverse(mut self) ``` Reverse the list in place. O(1) via reversible links. - **cost**: O(1) - **empty**: does nothing - **traps**: never Examples: - `var a = LinkedList.from_list([1, 2, 3]); a.reverse(); a.each().collect() == [3, 2, 1]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/deque.cp#L503) ### `LinkedList.clear` ```cp fn clear(mut self) ``` Remove all elements. - **cost**: O(1) - **traps**: never Examples: - `var a = LinkedList.from_list([1, 2]); a.clear(); a.is_empty` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/deque.cp#L512) ### `LinkedList.each` ```cp fn each(self) -> yields T ``` Yield elements front to back. - **cost**: O(1) per step - **empty**: yields nothing - **order**: front to back - **traps**: never Examples: - `LinkedList.from_list([1, 2]).each().collect() == [1, 2]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/deque.cp#L525) ### `LinkedList.each_rev` ```cp fn each_rev(self) -> yields T ``` Yield elements back to front. - **cost**: O(1) per step - **empty**: yields nothing - **order**: back to front - **traps**: never Examples: - `LinkedList.from_list([1, 2]).each_rev().collect() == [2, 1]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/deque.cp#L538) --- # dp URL: /docs/ref/std/dp Generated from [spec/std/dp.cp](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dp.cp) by `cpl doc --format json`. ## `Line` ```cp pub struct Line(k: Int, m: Int) ``` O(1) per evaluation. The line `k * x + m`, the usual entry of a `LiChao`. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dp.cp#L16) ### `Line.at` ```cp fn at(self, x: Int) -> Int ``` Evaluate the line at `x`: `k * x + m`. - **cost**: O(1) - **traps**: when `k * x + m` overflows `Int` Examples: - `Line(2, 3).at(4) == 11` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dp.cp#L22) ## `LiChao` ```cp pub struct LiChao(pick: (K, K) -> K, lo: Int, hi: Int) ``` O(log n) per `at`, O(log n) per whole-line `add`, O(log^2 n) on a segment. The lower (`LiChao(min, over: 0..=1e9)`) or upper (`max`) envelope of lines over the integer coordinates `over`. A line is anything with `at(self, x: Int) -> K`, so a struct whose `at` returns `(cost, used)` breaks ties by its second field with the same tree. Law: two lines cross at most once on `xs`. `add` is O(log n) for a whole line and O(log^2 n) on a segment (`on: lo..=hi`), `at` and `line_at` O(log n), for n = `xs.len`; memory is O(lines) cells, allocated as lines arrive. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dp.cp#L32) ### `LiChao.new` ```cp fn new(pick: (K, K) -> K, over: Range) -> LiChao ``` An empty envelope over the integer coordinates `over`, keeping at each `x` the value `pick` prefers (`min` for the lower envelope, `max` for the upper). No cell is allocated until a line arrives. `over` may be written half-open (`0..n`) or closed (`0..=hi`); the coordinates are its points. - **cost**: O(1) - **empty**: an empty `over` traps - **order**: no sequence is returned; coordinates run in `over`'s order - **traps**: when `over` is empty Examples: - `LiChao(min, over: 0..=10).at(5) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dp.cp#L49) ### `LiChao.clear` ```cp fn clear(mut self) ``` Forget every line, keeping `pick` and `over`, so the tree can be reused (between test cases, say) without reallocating. - **cost**: O(1) amortized - **traps**: never Examples: - `var t = LiChao(min, over: 0..=10); t.add(Line(1, 0)); t.clear(); t.at(3) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dp.cp#L59) ### `LiChao.at` ```cp fn at(self, x: Int) -> ?K ``` The best value at `x` over every line covering `x`, as chosen by `pick`, or `None` when no line covers `x` (nothing added yet, or only segments that miss `x`). - **cost**: O(log n) for n = `over.len` - **ties**: equal values are one value; which line produced it does not matter - **traps**: when `x` is not in `over` Examples: - `var t = LiChao(min, over: 0..=10); t.add(Line(1, 0)); t.add(Line(-1, 6)); t.at(1) == Some(1) and t.at(5) == Some(1)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dp.cp#L69) ### `LiChao.line_at` ```cp fn line_at(self, x: Int) -> ?L ``` The line attaining `at(x)`, or `None` when no line covers `x`. When several lines tie at `x` any of them may be returned; make `K` carry a tie-breaking second field (as with `at` returning `(cost, used)`) when the choice matters. - **cost**: O(log n) for n = `over.len` - **ties**: unspecified among lines with equal values at `x`; break ties through `K` - **traps**: when `x` is not in `over` Examples: - `var t = LiChao(min, over: 0..=10); t.add(Line(1, 0)); t.add(Line(-1, 6)); t.line_at(8) == Some(Line(-1, 6))` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dp.cp#L97) ### `LiChao.add` ```cp fn add(mut self, line: L, on: ?Range = None) ``` Add `line` on every coordinate of `over`, or only on the coordinates of `on` (`on: lo..=hi`). Later `at(x)` calls consider the line only where it was added. Law: any two lines added cross at most once on `over` (true for straight lines, and for `at` functions whose difference changes sign at most once). - **cost**: O(log n) for a whole line, O(log^2 n) on a segment, for n = `over.len`; at most one new cell per level - **empty**: an empty `on` adds nothing - **traps**: when `on` reaches outside `over` Examples: - `var t = LiChao(max, over: 0..=10); t.add(Line(0, 5), on: 2..=4); t.at(3) == Some(5) and t.at(5) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dp.cp#L125) ### `LiChao.wins` ```cp fn wins(self, a: K, b: K) -> Bool ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dp.cp#L143) ### `LiChao.kid` ```cp fn kid(mut self, i: Int, right_side: Bool) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dp.cp#L145) ### `LiChao.settle` ```cp fn settle(mut self, at: Int, lo: Int, hi: Int, line: L) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dp.cp#L157) ## `MongePath` ```cp pub struct MongePath(nodes: List, cost: (N, N) -> K) ``` O(1) per step; the next cut's optimum after O(1) amortized calls of `cost`. `monge_path` one node at a time, for a DP whose next weight depends on the optimum just found. `next()` returns the optimum at the next node and the node before it; `val(i)` reads any node already reached. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dp.cp#L390) ### `MongePath.w` ```cp fn w(self, j: Int, i: Int) -> K ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dp.cp#L402) ### `MongePath.setup` ```cp fn setup(mut self) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dp.cp#L404) ### `MongePath.next` ```cp fn next(mut self) -> (val: K, prev: Int) ``` Reach the next node: return the optimum at node `len` and the index of the node before it, then grow `len` by one. `cost` may read values already reached through `val`, so the weights can depend on earlier optima. - **cost**: O(1) amortized calls of `cost` - **ties**: among equal totals the predecessor found by LARSCH - **traps**: when every node has been reached (`len == nodes.len`) Examples: - `var p = MongePath([0, 1, 2], (a, b) => (b - a) * (b - a)); p.next(); p.next() == (val: 2, prev: 1)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dp.cp#L424) ### `MongePath.val` ```cp fn val(self, i: Int) -> K ``` The optimum at node `i`, which must already be reached; `val(0)` is 0. - **cost**: O(1) - **traps**: when `i < 0` or `i >= len` Examples: - `var p = MongePath([0, 1, 2], (a, b) => (b - a) * (b - a)); p.next(); p.val(1) == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dp.cp#L495) ### `MongePath.len` ```cp fn len(self) -> Int ``` The number of nodes reached so far, `nodes.first` included, so a fresh `MongePath` has `len == 1`. - **cost**: O(1) - **traps**: never Examples: - `MongePath([0, 1, 2], (a, b) => (b - a) * (b - a)).len == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dp.cp#L503) ## `MonotoneHull` ```cp pub struct MonotoneHull

(pick: (Int, Int) -> Int = min) ``` O(1) amortized per `add` and per `at_next`, O(log n) per `at`. The convex hull trick for lines added in slope order: falling slopes for `pick: min`, rising for `max` (an out-of-order slope traps). The online form of `LiChao` when slopes arrive sorted and no x-range is known. Each line may carry a `tag` (a photo count, a parent index); `best_next` returns the winning line's tag, and equal values go to the smaller tag, which is the tie rule `aliens` needs. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dp.cp#L558) ### `MonotoneHull.sign` ```cp fn sign(self) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dp.cp#L566) ### `MonotoneHull.val_at` ```cp fn val_at(self, i: Int, x: Int) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dp.cp#L568) ### `MonotoneHull.covered` ```cp fn covered(self, k: Int, m: Int) -> Bool ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dp.cp#L570) ### `MonotoneHull.pop_line` ```cp fn pop_line(mut self) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dp.cp#L574) ### `MonotoneHull.add` ```cp fn add(mut self, line: Line, tag: P = ()) ``` Add `line`, with `tag`. Slopes must arrive in order: non-increasing for `pick: min`, non-decreasing for `max`. A line of equal slope keeps only the better intercept, and lines that are never best are dropped. - **cost**: O(1) amortized - **traps**: when the slope goes back Examples: - `var h = MonotoneHull<()>(min); h.add(Line(2, 0)); h.add(Line(-1, 3)); h.at(0) == Some(0) and h.at(2) == Some(1)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dp.cp#L587) ### `MonotoneHull.best_next` ```cp fn best_next(mut self, x: Int) -> ?(val: Int, tag: P) ``` The best value at `x` with the tag of the line attaining it, for an `x` that never decreases between calls (a pointer walks the hull). `None` when empty. - **cost**: O(1) amortized - **ties**: equal values go to the smaller tag (the rule `aliens` needs) - **traps**: when `x` is less than the previous `best_next` or `at_next` argument Examples: - `var h = MonotoneHull(min); h.add(Line(1, 0), tag: 7); h.add(Line(-1, 2), tag: 3); h.best_next(1) == Some((val: 1, tag: 3))` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dp.cp#L607) ### `MonotoneHull.at` ```cp fn at(self, x: Int) -> ?Int ``` The best value at any `x`, by binary search on the hull; `None` when empty. - **cost**: O(log n) - **ties**: only the value is kept - **traps**: never Examples: - `var h = MonotoneHull<()>(min); h.add(Line(2, 0)); h.add(Line(-1, 3)); h.at(5) == Some(-2)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dp.cp#L622) ### `MonotoneHull.at_next` ```cp fn at_next(mut self, x: Int) -> ?Int ``` `at(x)` for an `x` that never decreases between calls; `None` when empty. - **cost**: O(1) amortized - **ties**: only the value is kept - **traps**: when `x` is less than the previous `best_next` or `at_next` argument Examples: - `var h = MonotoneHull<()>(min); h.add(Line(2, 0)); h.add(Line(-1, 3)); h.at_next(0) == Some(0) and h.at_next(2) == Some(1)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dp.cp#L636) ### `MonotoneHull.len` ```cp fn len(self) -> Int ``` The number of lines kept on the hull (dominated lines are not counted). - **cost**: O(1) - **traps**: never Examples: - `var h = MonotoneHull<()>(min); h.add(Line(2, 0)); h.add(Line(-1, 3)); h.len == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dp.cp#L643) ### `MonotoneHull.clear` ```cp fn clear(mut self) ``` Remove every line and reset the `at_next` pointer, keeping `pick`. - **cost**: O(1) - **traps**: never Examples: - `var h = MonotoneHull<()>(min); h.add(Line(2, 0)); h.clear(); h.at(0) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dp.cp#L650) ## `LineContainer` ```cp pub struct LineContainer(pick: (Int, Int) -> Int = min) ``` O(log n) amortized per `add`, O(log n) per `at`. The convex hull trick with lines in any order and queries at any `x`, no coordinate range needed (KACTL's line container). Use `LiChao` for segment adds or non-line functions. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dp.cp#L661) ### `LineContainer.sign` ```cp fn sign(self) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dp.cp#L674) ### `LineContainer.floor_div` ```cp fn floor_div(a: Int, b: Int) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dp.cp#L676) ### `LineContainer.meet` ```cp fn meet(self, x: Int, y: Int) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dp.cp#L682) ### `LineContainer.split` ```cp fn split(mut self, t: Int, k: Int) -> (Int, Int) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dp.cp#L688) ### `LineContainer.merge` ```cp fn merge(mut self, a: Int, b: Int) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dp.cp#L699) ### `LineContainer.end` ```cp fn end(self, t: Int, right: Bool) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dp.cp#L709) ### `LineContainer.drop_end` ```cp fn drop_end(mut self, t: Int, right: Bool) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dp.cp#L715) ### `LineContainer.best` ```cp fn best(self, x: Int) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dp.cp#L730) ### `LineContainer.add` ```cp fn add(mut self, line: Line) ``` Add `line`; slopes may arrive in any order. Lines that are never best are dropped. - **cost**: O(log n) amortized - **traps**: never Examples: - `var c = LineContainer(max); c.add(Line(1, 0)); c.add(Line(-1, 4)); c.at(0) == Some(4) and c.at(3) == Some(3)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dp.cp#L743) ### `LineContainer.at` ```cp fn at(self, x: Int) -> ?Int ``` The best value at `x`, or `None` when empty. - **cost**: O(log n) - **ties**: only the value is kept - **traps**: never Examples: - `var c = LineContainer(min); c.add(Line(1, 0)); c.add(Line(-1, 4)); c.at(0) == Some(0) and c.at(3) == Some(1)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dp.cp#L795) ### `LineContainer.line_at` ```cp fn line_at(self, x: Int) -> ?Line ``` The line attaining `at(x)`, or `None` when empty. - **cost**: O(log n) - **ties**: unspecified among lines with equal values at `x` - **traps**: never Examples: - `var c = LineContainer(max); c.add(Line(1, 0)); c.add(Line(-1, 4)); c.line_at(3) == Some(Line(1, 0))` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dp.cp#L804) ### `LineContainer.len` ```cp fn len(self) -> Int ``` The number of lines kept (dominated lines are not counted). - **cost**: O(1) - **traps**: never Examples: - `var c = LineContainer(max); c.add(Line(1, 0)); c.add(Line(-1, 4)); c.len == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dp.cp#L812) ## `Step` ```cp pub struct Step(state: S, depth: Int) ``` One state reached by `backtrack`. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dp.cp#L921) ### `Step.prune` ```cp fn prune(self) ``` Skip every state below this one: `backtrack` does not call `next` on it. Has effect only on the step just yielded, before the `for` body continues. - **cost**: O(1) - **traps**: never Examples: - with `next` as `x => if x < 4: [2 * x, 2 * x + 1] else: []`, a `for s in backtrack(1, next)` body that calls `s.prune()` when `s.state == 2` sees the states `[1, 2, 3, 6, 7]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dp.cp#L928) --- # dsu URL: /docs/ref/std/dsu Generated from [spec/std/dsu.cp](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp) by `cpl doc --format json`. ## `Mark` ```cp pub struct Mark(at ``` A point in the history of a structure that can step back in time, returned by `mark()` and taken by `undo_to`. Its own type, so it can't be mixed up with a count or an index. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L5) ## `Dsu` ```cp pub struct Dsu ``` Union-find with path halving and union by size. `find`, `unite`, `same` and `size` are O(alpha(n)) amortized; memory is one `[V]` array (4 B/vertex). It can also step back in time: `let snap = d.mark()` remembers the present and `d.undo_to(snap)` returns to it. From the first `mark` on, paths are no longer shortened (a shortened path cannot be restored), so every operation is O(log n) and each `unite` costs one entry of memory until it is undone. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L14) ### `Dsu.joined` ```cp joined: List ``` Pairs `[child_ord, old_neg_size]` pushed flat since the first `mark`. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L18) ### `Dsu.new` ```cp fn new(rollback: Bool = false) -> Dsu ``` A union-find over `V` with every position in its own set. Pass `rollback: true` to switch path shortening off from the start, as the first `mark()` would. - **cost**: O(n) for n = `V.count`; one `[V]` array - **traps**: never Examples: - `let d = Dsu<0..3>(); d.components == 3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L27) ### `Dsu.find_ord` ```cp fn find_ord(self, start: Int) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L29) ### `Dsu.find` ```cp fn find(self, v: V) -> V ``` The representative of `v`'s set: the root that union by size kept. Two positions are in one set exactly when they have the same representative. Halves the path it walks through `@cache`, so a read-only `Dsu` answers it too; from the first `mark` on, paths are left alone. - **cost**: O(alpha(n)) amortized; O(log n) after the first `mark` - **ties**: None; the representative is fixed by the merges (larger set's root, `a`'s root on equal sizes) - **traps**: never Examples: - `var d = Dsu<0..4>(); d.unite(2, 3); d.find(3) == 2 and d.find(0) == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L49) ### `Dsu.mark` ```cp fn mark(mut self) -> Mark ``` The present, to return to with [`undo_to`](Dsu.undo_to). The first call switches path shortening off for good. - **cost**: O(1) - **traps**: never Examples: - `var d = Dsu<0..3>(); let m = d.mark(); d.unite(0, 1); d.undo_to(m); d.components == 3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L57) ### `Dsu.undo_to` ```cp fn undo_to(mut self, snap: Mark) ``` Undoes every `unite` made since `snap = mark()`, newest first, so the sets, sizes and representatives are exactly what they were at the mark. Marks nest: undoing to an older mark passes over newer ones. - **cost**: O(1) per undone `unite` - **traps**: when `snap` lies after the present (its changes were already undone) Examples: - `var d = Dsu<0..3>(); d.unite(0, 1); let m = d.mark(); d.unite(1, 2); d.undo_to(m); d.same(0, 1) and not d.same(0, 2)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L68) ### `Dsu.unite` ```cp fn unite(mut self, a: V, b: V) -> Bool ``` Merges the sets of `a` and `b`; `false` if they were already one set (nothing changes then). The root of the larger set is kept; on equal sizes `a`'s root is kept. - **cost**: O(alpha(n)) amortized; O(log n) after the first `mark`, plus one log entry - **traps**: never Examples: - `var d = Dsu<0..3>(); d.unite(0, 1) and not d.unite(1, 0)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L88) ### `Dsu.merge` ```cp fn merge(mut self, a: V, b: V) -> ?(kept: V, merged: V) ``` As [`unite`](Dsu.unite), but says which root stayed and which went under it, so data kept per set can follow: `if let (kept, merged) = d.merge(a, b): sum[kept] += sum[merged]`. `None` if `a` and `b` were already one set. - **cost**: as `unite` - **traps**: never Examples: - `var d = Dsu<0..3>(); d.merge(1, 0) == Some((kept: 1, merged: 0))` - `var d = Dsu<0..3>(); d.unite(0, 1); d.merge(2, 1) == Some((kept: 0, merged: 2))` - `var d = Dsu<0..3>(); d.unite(0, 1); d.merge(1, 0) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L99) ### `Dsu.same` ```cp fn same(self, a: V, b: V) -> Bool ``` Whether `a` and `b` are in the same set. - **cost**: O(alpha(n)) amortized; O(log n) after the first `mark` - **traps**: never Examples: - `var d = Dsu<0..3>(); d.unite(0, 2); d.same(2, 0) and not d.same(0, 1)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L119) ### `Dsu.size` ```cp fn size(self, v: V) -> Int ``` The number of positions in `v`'s set, `v` included. - **cost**: O(alpha(n)) amortized; O(log n) after the first `mark` - **traps**: never Examples: - `var d = Dsu<0..3>(); d.unite(0, 2); d.size(2) == 2 and d.size(1) == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L126) ### `Dsu.components` ```cp fn components(self) -> Int ``` The number of sets: `V.count` minus the successful `unite`s still in effect. - **cost**: O(1) - **traps**: never Examples: - `var d = Dsu<0..4>(); d.unite(0, 1); d.unite(1, 0); d.components == 3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L136) ### `Dsu.roots` ```cp fn roots(self) -> yields V ``` The representative of each set, once each, lazily. - **cost**: O(n) for the whole walk, no allocation - **empty**: yields nothing when `V` is empty - **order**: increasing positions of `V` - **traps**: never Examples: - `var d = Dsu<0..4>(); d.unite(3, 1); d.roots().collect() == [0, 2, 3]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L145) ### `Dsu.groups` ```cp fn groups(self) -> List> ``` Every set as a list of its positions, each position in exactly one list. - **cost**: O(n alpha(n)); allocates the lists - **empty**: `[]` when `V` is empty - **order**: lists by their least position, positions increasing within each - **traps**: never Examples: - `var d = Dsu<0..4>(); d.unite(3, 1); d.groups() == [[0], [1, 3], [2]]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L157) ## `DsuOf` ```cp pub struct DsuOf ``` Union-find where every set carries a value of type `T`. When two sets merge, the merged set gets `join(value of a's set, value of b's set)` for `unite(a, b)`, whichever root is kept, so a directional join like `(_, b) => b` means "b's value wins". Costs are those of `Dsu`, plus one `join` per merge; memory is three `[V]` arrays. `mark` and `undo_to` step back in time like `Dsu`'s, and restore the values too: every merge and every `set` since the mark is undone, O(1) each. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L175) ### `DsuOf.log` ```cp log: List<(V, V, T)> ``` Since the first `mark`, one entry per change: the root that went under another (the root itself for a `set`), the root whose value changed, and that value before. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L183) ### `DsuOf.new` ```cp fn new(init: (V) -> T, join: (T, T) -> T) -> DsuOf ``` A union-find over `V` with every position alone, the set of `v` holding `init(v)`, and `join` combining the values of two sets when they merge. - **cost**: O(n) calls of `init`; three `[V]` arrays - **traps**: never Examples: - `let d = DsuOf<0..3, Int>(init: v => v + 1, join: (x, y) => x + y); d.get(2) == 3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L192) ### `DsuOf.find` ```cp fn find(self, v: V) -> V ``` The representative of `v`'s set, as for [`Dsu.find`](Dsu.find). Halves paths through `@cache` until the first `mark`. - **cost**: O(alpha(n)) amortized; O(log n) after the first `mark` - **ties**: None; the representative is fixed by the merges (larger set's root, `a`'s root on equal sizes) - **traps**: never Examples: - `var d = DsuOf<0..3, Int>(init: v => v, join: (x, y) => x + y); d.unite(1, 2); d.find(2) == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L202) ### `DsuOf.get` ```cp fn get(self, v: V) -> T ``` The value of `v`'s set. - **cost**: O(alpha(n)) amortized; O(log n) after the first `mark` - **traps**: never Examples: - `var d = DsuOf<0..3, Int>(init: v => v + 1, join: (x, y) => x + y); d.unite(0, 2); d.get(2) == 4 and d.get(1) == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L215) ### `DsuOf.set` ```cp fn set(mut self, v: V, x: T) ``` Replaces the value of `v`'s whole set with `x`. - **cost**: O(alpha(n)) amortized; O(log n) after the first `mark`, plus one log entry - **traps**: never Examples: - `var d = DsuOf<0..3, Int>(init: v => v, join: (x, y) => x + y); d.unite(0, 1); d.set(1, 7); d.get(0) == 7` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L224) ### `DsuOf.unite` ```cp fn unite(mut self, a: V, b: V) -> Bool ``` Merges the sets of `a` and `b`, giving the merged set `join(value of a's set, value of b's set)` in that argument order whichever root is kept; `false` if they were already one set (the value is left alone then and `join` is not called). The root of the larger set is kept; on equal sizes `a`'s root is kept. - **cost**: as [`Dsu.unite`](Dsu.unite), plus one call of `join` - **traps**: never Examples: - `var d = DsuOf<0..3, Int>(init: v => v, join: (_, y) => y); d.unite(2, 0); d.get(2) == 0` - `var d = DsuOf<0..3, Int>(init: v => v, join: (x, y) => x + y); d.unite(0, 1); not d.unite(1, 0) and d.get(0) == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L239) ### `DsuOf.merge` ```cp fn merge(mut self, a: V, b: V) -> ?(kept: V, merged: V) ``` As [`unite`](DsuOf.unite), but says which root stayed and which went under it. `None` if `a` and `b` were already one set. - **cost**: as `unite` - **traps**: never Examples: - `var d = DsuOf<0..3, Int>(init: v => v, join: (x, y) => x + y); d.merge(2, 1) == Some((kept: 2, merged: 1))` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L258) ### `DsuOf.same` ```cp fn same(self, a: V, b: V) -> Bool ``` Whether `a` and `b` are in the same set. - **cost**: O(alpha(n)) amortized; O(log n) after the first `mark` - **traps**: never Examples: - `var d = DsuOf<0..3, Int>(init: v => v, join: (x, y) => x + y); d.unite(0, 2); d.same(0, 2) and not d.same(1, 2)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L271) ### `DsuOf.size` ```cp fn size(mut self, v: V) -> Int ``` The number of positions in `v`'s set, `v` included. - **cost**: O(alpha(n)) amortized; O(log n) after the first `mark` - **traps**: never Examples: - `var d = DsuOf<0..3, Int>(init: v => v, join: (x, y) => x + y); d.unite(0, 2); d.size(0) == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L278) ### `DsuOf.components` ```cp fn components(self) -> Int ``` The number of sets. - **cost**: O(1) - **traps**: never Examples: - `var d = DsuOf<0..3, Int>(init: v => v, join: (x, y) => x + y); d.unite(0, 2); d.components == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L287) ### `DsuOf.roots` ```cp fn roots(self) -> yields V ``` The representative of each set, once each, lazily. - **cost**: O(n) for the whole walk, no allocation - **empty**: yields nothing when `V` is empty - **order**: increasing positions of `V` - **traps**: never Examples: - `var d = DsuOf<0..3, Int>(init: v => v, join: (x, y) => x + y); d.unite(2, 0); d.roots().collect() == [1, 2]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L296) ### `DsuOf.values` ```cp fn values(self) -> yields T ``` The value of each set, once each, lazily: one per root, in the order of [`roots`](DsuOf.roots). O(1) to make. - **cost**: O(n) for the whole walk, no allocation - **empty**: yields nothing when `V` is empty - **order**: by representative, increasing positions of `V` - **traps**: never Examples: - `var d = DsuOf<0..3, Int>(init: v => v + 1, join: (x, y) => x + y); d.unite(2, 0); d.values.collect() == [2, 4]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L308) ### `DsuOf.mark` ```cp fn mark(mut self) -> Mark ``` The present, to return to with [`undo_to`](DsuOf.undo_to). The first call switches path shortening off for good. - **cost**: O(1) - **traps**: never Examples: - `var d = DsuOf<0..2, Int>(init: v => v, join: (x, y) => x + y); let m = d.mark(); d.unite(0, 1); d.undo_to(m); d.get(0) == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L318) ### `DsuOf.undo_to` ```cp fn undo_to(mut self, snap: Mark) ``` Undoes every merge and every `set` made since `snap = mark()`, newest first, restoring the sets and their values exactly. - **cost**: O(1) per undone change - **traps**: when `snap` lies after the present (its changes were already undone) Examples: - `var d = DsuOf<0..2, Int>(init: v => v, join: (x, y) => x + y); let m = d.mark(); d.unite(0, 1); d.set(0, 9); d.undo_to(m); d.get(0) == 0 and d.get(1) == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L328) ### `DsuOf.groups` ```cp fn groups(mut self) -> List> ``` Every set as a list of its positions, as `Dsu.groups`; values are read with `get`. - **cost**: O(n alpha(n)); allocates the lists - **empty**: `[]` when `V` is empty - **order**: lists by their least position, positions increasing within each - **traps**: never Examples: - `var d = DsuOf<0..3, Int>(init: v => v, join: (x, y) => x + y); d.unite(2, 0); d.groups() == [[0, 2], [1]]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L344) ## `ParityDsu` ```cp pub struct ParityDsu ``` Union-find that knows, for two positions of one set, whether they are on the same side or on opposite sides: two-colouring, parity constraints, `x[a] xor x[b] == d`. `unite` and `diff` are O(log n) (union by size; paths are never shortened, so `mark` and `undo_to` work at any time, O(1) per undone `unite`). Memory is three `[V]` arrays. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L359) ### `ParityDsu.flip` ```cp flip: [V]Bool ``` Is the position on the other side from `up` of it? [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L363) ### `ParityDsu.log` ```cp log: List<(V, Bool)> ``` One entry per `unite` that changed something: the root it hung under another root, or (with `false`) the root of a set where it found a contradiction. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L366) ### `ParityDsu.new` ```cp fn new() -> ParityDsu ``` A parity union-find over `V` with every position alone and nothing known. - **cost**: O(n); three `[V]` arrays - **traps**: never Examples: - `let d = ParityDsu<0..3>(); d.consistent and d.diff(0, 1) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L374) ### `ParityDsu.find` ```cp fn find(self, v: V) -> (root: V, flip: Bool) ``` The representative of `v`'s set and whether `v` is on the other side from it. - **cost**: O(log n) - **ties**: None; the representative is fixed by the merges (larger set's root, `a`'s root on equal sizes) - **traps**: never Examples: - `var d = ParityDsu<0..3>(); d.unite(0, 1); d.find(1) == (root: 0, flip: true)` - `let d = ParityDsu<0..3>(); d.find(2) == (root: 2, flip: false)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L384) ### `ParityDsu.unite` ```cp fn unite(mut self, a: V, b: V, differ: Bool = true) -> Bool ``` Records that `a` and `b` are on opposite sides (`differ: false`: the same side). An edge of a graph is `unite(u, v)`. Returns `false` when that contradicts what is already known: nothing is merged, the contradiction is counted, and [`consistent`](ParityDsu.consistent) stays false until it is undone. A constraint that is already implied returns `true` and changes nothing. Merging keeps the larger set's root, `a`'s root on equal sizes. - **cost**: O(log n), plus one log entry when it merges or contradicts - **traps**: never Examples: - `var d = ParityDsu<0..3>(); d.unite(0, 1); d.unite(1, 2); not d.unite(0, 2) and not d.consistent` - `var d = ParityDsu<0..3>(); d.unite(0, 1); d.unite(1, 2); d.unite(0, 2, differ: false) and d.consistent` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L403) ### `ParityDsu.diff` ```cp fn diff(self, a: V, b: V) -> ?Bool ``` Whether `a` and `b` are on opposite sides; `None` when nothing relates them yet. - **cost**: O(log n) - **traps**: never Examples: - `var d = ParityDsu<0..3>(); d.unite(0, 1); d.unite(1, 2); d.diff(0, 2) == Some(false) and d.diff(1, 0) == Some(true)` - `ParityDsu<0..3>().diff(0, 2) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L424) ### `ParityDsu.same` ```cp fn same(self, a: V, b: V) -> Bool ``` Whether `a` and `b` are in the same set, so that their relative side is known. - **cost**: O(log n) - **traps**: never Examples: - `var d = ParityDsu<0..3>(); d.unite(0, 1); d.same(1, 0) and not d.same(0, 2)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L434) ### `ParityDsu.size` ```cp fn size(self, v: V) -> Int ``` The number of positions in `v`'s set, `v` included. - **cost**: O(log n) - **traps**: never Examples: - `var d = ParityDsu<0..3>(); d.unite(0, 1); d.unite(1, 2); d.size(2) == 3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L441) ### `ParityDsu.consistent` ```cp fn consistent(self) -> Bool ``` Whether no contradiction is in effect: every `unite` since the last undone one agreed with those before it. For a graph: is it two-colourable? - **cost**: O(1) - **traps**: never Examples: - `var d = ParityDsu<0..3>(); d.unite(0, 1); d.unite(1, 2); d.unite(2, 0); not d.consistent` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L449) ### `ParityDsu.mark` ```cp fn mark(self) -> Mark ``` The present, to return to with [`undo_to`](ParityDsu.undo_to). Paths are never shortened, so marking changes nothing else. - **cost**: O(1) - **traps**: never Examples: - `var d = ParityDsu<0..2>(); let m = d.mark(); d.unite(0, 1); d.undo_to(m); d.diff(0, 1) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L457) ### `ParityDsu.undo_to` ```cp fn undo_to(mut self, snap: Mark) ``` Takes back every `unite` since `snap = mark()`, contradictions included, newest first. - **cost**: O(1) per undone `unite` - **traps**: when `snap` lies after the present (its changes were already undone) Examples: - `var d = ParityDsu<0..3>(); d.unite(0, 1); d.unite(1, 2); let m = d.mark(); d.unite(2, 0); d.undo_to(m); d.consistent` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L464) ## `PotentialDsu` ```cp pub struct PotentialDsu ``` Weighted (potential / difference-constraint) union-find over domain `V` with `Mark` rollback. Maintains constraints of the form `val[b] - val[a] == w`. All operations are O(log n); `mark` and `consistent` are O(1); `undo_to` is O(1) per undone step. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L477) ### `PotentialDsu.new` ```cp fn new(op: ?G = None) -> PotentialDsu ``` A potential union-find over `V` with every position alone at the identity potential. Constraints combine with the group operation `op`, `+` on `Int` when it is `None`. - **cost**: O(n); three `[V]` arrays - **traps**: never Examples: - `let d = PotentialDsu<0..3>(); d.components == 3 and d.consistent` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L491) ### `PotentialDsu.find` ```cp fn find(self, v: V) -> (root: V, offset: Int) ``` The representative of `v`'s set and `val[v] - val[root]`. - **cost**: O(log n) - **ties**: None; the representative is fixed by the merges (larger set's root, `a`'s root on equal sizes) - **traps**: never Examples: - `var d = PotentialDsu<0..3>(); d.unite(0, 1, 5); d.find(1) == (root: 0, offset: 5)` - `let d = PotentialDsu<0..3>(); d.find(2) == (root: 2, offset: 0)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L502) ### `PotentialDsu.unite` ```cp fn unite(mut self, a: V, b: V, w: Int) -> Bool ``` Records `val[b] - val[a] == w`. Returns `false` when that contradicts what is already known: nothing is merged, the contradiction is counted, and [`consistent`](PotentialDsu.consistent) stays false until it is undone. A constraint that is already implied returns `true` and changes nothing. Merging keeps the larger set's root, `a`'s root on equal sizes. - **cost**: O(log n), plus one log entry when it merges or contradicts - **traps**: never Examples: - `var d = PotentialDsu<0..3>(); d.unite(0, 1, 5); d.unite(1, 2, 3); not d.unite(0, 2, 7) and d.unite(0, 2, 8)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L520) ### `PotentialDsu.diff` ```cp fn diff(self, a: V, b: V) -> ?Int ``` `val[b] - val[a]` when `a` and `b` are in the same set, else `None`. - **cost**: O(log n) - **traps**: never Examples: - `var d = PotentialDsu<0..3>(); d.unite(0, 1, 5); d.unite(1, 2, 3); d.diff(0, 2) == Some(8) and d.diff(2, 0) == Some(-8)` - `PotentialDsu<0..3>().diff(0, 1) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L548) ### `PotentialDsu.same` ```cp fn same(self, a: V, b: V) -> Bool ``` Whether `a` and `b` are in the same set, so that their difference is known. - **cost**: O(log n) - **traps**: never Examples: - `var d = PotentialDsu<0..3>(); d.unite(2, 0, 1); d.same(0, 2) and not d.same(0, 1)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L558) ### `PotentialDsu.size` ```cp fn size(self, v: V) -> Int ``` The number of positions in `v`'s set, `v` included. - **cost**: O(log n) - **traps**: never Examples: - `var d = PotentialDsu<0..3>(); d.unite(2, 0, 1); d.size(0) == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L565) ### `PotentialDsu.components` ```cp fn components(self) -> Int ``` The number of sets. - **cost**: O(1) - **traps**: never Examples: - `var d = PotentialDsu<0..3>(); d.unite(0, 1, 5); d.components == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L572) ### `PotentialDsu.consistent` ```cp fn consistent(self) -> Bool ``` Whether no contradiction is in effect. - **cost**: O(1) - **traps**: never Examples: - `var d = PotentialDsu<0..2>(); d.unite(0, 1, 5); not d.unite(1, 0, 5) and not d.consistent` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L579) ### `PotentialDsu.mark` ```cp fn mark(self) -> Mark ``` The present, to return to with [`undo_to`](PotentialDsu.undo_to). - **cost**: O(1) - **traps**: never Examples: - `var d = PotentialDsu<0..2>(); let m = d.mark(); d.unite(0, 1, 5); d.undo_to(m); d.diff(0, 1) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L586) ### `PotentialDsu.undo_to` ```cp fn undo_to(mut self, snap: Mark) ``` Takes back every `unite` since `snap = mark()`, contradictions included, newest first. - **cost**: O(1) per undone `unite` - **traps**: when `snap` lies after the present (its changes were already undone) Examples: - `var d = PotentialDsu<0..2>(); d.unite(0, 1, 5); let m = d.mark(); d.unite(1, 0, 5); d.undo_to(m); d.consistent and d.diff(0, 1) == Some(5)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L593) ## `RollbackArray` ```cp pub struct RollbackArray ``` Domain-indexed array `[D]T` with `Mark` rollback. `get`, `set`, and `mark` are O(1); `undo_to` is O(1) per undone write. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L606) ### `RollbackArray.new` ```cp fn new(init: D -> T) -> RollbackArray ``` An array over `D` holding `init(i)` at each `i`, that can step back to any mark. - **cost**: O(n) calls of `init`, for n = `D.count` - **traps**: never Examples: - `let a = RollbackArray<0..3, Int>(init: i => i * i); a.get(2) == 4` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L615) ### `RollbackArray.get` ```cp fn get(self, i: D) -> T ``` The current value at `i`. - **cost**: O(1) - **traps**: never Examples: - `var a = RollbackArray<0..3, Int>(init: i => i); a.set(1, 7); a.get(1) == 7 and a.get(2) == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L622) ### `RollbackArray.set` ```cp fn set(mut self, i: D, val: T) ``` Sets `i` to `val`, logging the previous value so `undo_to` can restore it. Every `set` is logged, marked or not. - **cost**: O(1), plus one log entry - **traps**: never Examples: - `var a = RollbackArray<0..2, Int>(init: _ => 0); a.set(0, 5); a.get(0) == 5` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L630) ### `RollbackArray.mark` ```cp fn mark(self) -> Mark ``` The present, to return to with [`undo_to`](RollbackArray.undo_to). - **cost**: O(1) - **traps**: never Examples: - `var a = RollbackArray<0..2, Int>(init: _ => 0); let m = a.mark(); a.set(1, 3); a.undo_to(m); a.get(1) == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L639) ### `RollbackArray.undo_to` ```cp fn undo_to(mut self, snap: Mark) ``` Reverts every `set` since `snap = mark()`, newest first, so each position holds what it held at the mark. - **cost**: O(1) per undone `set` - **traps**: when `snap` lies after the present (its changes were already undone) Examples: - `var a = RollbackArray<0..2, Int>(init: _ => 0); let m = a.mark(); a.set(0, 5); a.set(0, 6); a.undo_to(m); a.get(0) == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L647) ## `PersistentDsu` ```cp pub struct PersistentDsu ``` Path-copying persistent disjoint-set union over domain `V`. Every version remains readable; `find`, `unite`, `same`, and `size` run in O(log^2 n). [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L654) ### `PersistentDsu.new` ```cp fn new() -> PersistentDsu ``` A persistent union-find over `V` holding version 0, every position in its own set. - **cost**: O(n) - **traps**: never Examples: - `let d = PersistentDsu<0..3>(); not d.same(d.base, 0, 1)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L665) ### `PersistentDsu.build` ```cp fn build(mut self, lo: Int, hi: Int) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L671) ### `PersistentDsu.get` ```cp fn get(self, root: Int, i: Int) -> (Int, Int) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L683) ### `PersistentDsu.put` ```cp fn put(mut self, t: Int, lo: Int, hi: Int, i: Int, cell: (Int, Int)) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L697) ### `PersistentDsu.root_ord` ```cp fn root_ord(self, ver: Int, start: Int) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L710) ### `PersistentDsu.base` ```cp fn base(self) -> Int ``` The handle of version 0, where every position is alone. - **cost**: O(1) - **traps**: never Examples: - `PersistentDsu<0..3>().base == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L724) ### `PersistentDsu.find` ```cp fn find(self, ver: Int, v: V) -> V ``` The representative of `v`'s set in version `ver`, chosen by union by size as in [`Dsu.find`](Dsu.find). - **cost**: O(log² n) - **ties**: None; the representative is fixed by the merges (larger set's root, `a`'s root on equal sizes) - **traps**: when `ver` is not a version handle of `self` Examples: - `var d = PersistentDsu<0..3>(); let v1 = d.unite(d.base, 2, 1); d.find(v1, 1) == 2 and d.find(d.base, 1) == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L733) ### `PersistentDsu.same` ```cp fn same(self, ver: Int, a: V, b: V) -> Bool ``` Whether `a` and `b` are in the same set in version `ver`. - **cost**: O(log² n) - **traps**: when `ver` is not a version handle of `self` Examples: - `var d = PersistentDsu<0..3>(); let v1 = d.unite(d.base, 0, 1); d.same(v1, 0, 1) and not d.same(d.base, 0, 1)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L740) ### `PersistentDsu.size` ```cp fn size(self, ver: Int, v: V) -> Int ``` The number of positions in `v`'s set in version `ver`, `v` included. - **cost**: O(log² n) - **traps**: when `ver` is not a version handle of `self` Examples: - `var d = PersistentDsu<0..3>(); let v1 = d.unite(d.base, 0, 1); d.size(v1, 1) == 2 and d.size(d.base, 1) == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L747) ### `PersistentDsu.unite` ```cp fn unite(mut self, ver: Int, a: V, b: V) -> Int ``` A new version equal to `ver` with the sets of `a` and `b` merged; `ver` itself is unchanged. Handles are numbered in creation order: the k-th call returns `k`. A call whose `a` and `b` are already one set in `ver` still returns a fresh handle, equal in content to `ver`. Merging keeps the larger set's root, `a`'s root on equal sizes. - **cost**: O(log² n) time and O(log n) memory - **traps**: when `ver` is not a version handle of `self` Examples: - `var d = PersistentDsu<0..3>(); let v1 = d.unite(d.base, 0, 1); let v2 = d.unite(d.base, 1, 2); v1 == 1 and v2 == 2 and d.same(v2, 1, 2) and not d.same(v2, 0, 1)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L760) ### `PersistentDsu.reserve` ```cp fn reserve(mut self, nodes: Int) ``` Preallocates room for at least `nodes` persistent-array nodes, so later `unite`s do not grow the pool. Changes no version. - **cost**: O(nodes) - **traps**: when `nodes < 0` Examples: - `var d = PersistentDsu<0..3>(); d.reserve(100); d.size(d.base, 0) == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/dsu.cp#L779) --- # fenwick URL: /docs/ref/std/fenwick Generated from [spec/std/fenwick.cp](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/fenwick.cp) by `cpl doc --format json`. ## `Fenwick` ```cp pub struct Fenwick ``` Point add and range sum over anything with `+` and `-` (`Int`, `Mod

`). `Fenwick()` starts at zero and `Fenwick(a)` from an array, in O(n). `add`, `prefix` and `sum` are O(log n); memory is n + 1 values. A range is one prefix minus another, so there is no "Fenwick on max": that is a `SegTree`. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/fenwick.cp#L9) ### `Fenwick.new` ```cp fn new(a: ?[D]T = None) -> Fenwick ``` A Fenwick tree over `D`: all zeros, or holding the values of `a` when given. The values must form a group under `+` and `-` (`Int`, `Mod

`, `F64`), since a range sum is one prefix minus another. - **cost**: O(|D|) time; memory |D| + 1 values - **empty**: an empty `D` gives a tree whose every sum is zero - **order**: positions keep the domain `D` (of `a`, when given) - **traps**: never Examples: - `Fenwick([1, 2, 3]).all == 6` - `Fenwick<0..3, Int>().all == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/fenwick.cp#L22) ### `Fenwick.add` ```cp fn add(mut self, i: D, x: T) ``` Add `x` to the value at position `i`: `a[i] += x`. - **cost**: O(log |D|) - **traps**: when `i` is outside `D` Examples: - `var f = Fenwick([1, 2, 3]); f.add(0, 5); f.fold(0..2) == 8` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/fenwick.cp#L37) ### `Fenwick.prefix` ```cp fn prefix(self, b: Cut) -> T ``` The sum of every position left of the boundary `b`. For a position `v`, `prefix(v.r)` includes `v` and `prefix(v.l)` does not; the start cut gives zero. - **cost**: O(log |D|) - **traps**: never (`b` is a cut of `D` by type) Examples: - `Fenwick([1, 2, 3]).prefix((0..2).r) == 3` - `Fenwick([1, 2, 3]).prefix((0..0).r) == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/fenwick.cp#L50) ### `Fenwick.fold` ```cp fn fold(self, r: Range) -> T ``` The sum over the positions of `r`: `prefix(r.r) - prefix(r.l)`. Accepts every range form (`l..r`, `l..=r`, `..i`, `i..`). - **cost**: O(log |D|) - **empty**: zero - **traps**: when a non-empty `r` reaches outside `D` Examples: - `Fenwick([1, 2, 3]).fold(1..3) == 5` - `Fenwick([1, 2, 3]).fold(2..2) == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/fenwick.cp#L66) ### `Fenwick.first_ge` ```cp fn first_ge(self, target: Int) -> ?Cut ``` The smallest boundary `b` with `prefix(b) >= target`, by binary lifting over the tree; `None` when even the whole sum is below `target`. A `target <= 0` gives the start cut. Correct only when every value is non-negative (prefix sums non-decreasing). - **cost**: O(log |D|) - **ties**: the leftmost qualifying cut - **traps**: never (negative values give an unspecified cut, not a trap) Examples: - `Fenwick([1, 2, 3]).first_ge(3) == Some((0..2).r)` - `Fenwick([1, 2, 3]).first_ge(7) == None` - `Fenwick([1, 2, 3]).first_ge(0) == Some((0..0).r)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/fenwick.cp#L79) ### `Fenwick.kth` ```cp fn kth(self, k: Int) -> ?D ``` The `k`-th item counting from 1, when position `d` holds `a[d]` items: the first `d` with `prefix(d.r) >= k`, or `None` when fewer than `k` items exist in total. Positions with value zero are never returned. For non-negative values. - **cost**: O(log |D|) - **ties**: the leftmost qualifying position - **traps**: when `k < 1` (negative values give an unspecified position, not a trap) Examples: - `Fenwick([1, 0, 2]).kth(2) == Some(2)` - `Fenwick([1, 0, 2]).kth(1) == Some(0)` - `Fenwick([1, 0, 2]).kth(4) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/fenwick.cp#L104) ### `Fenwick.get` ```cp fn get(self, i: D) -> T ``` The current value at position `i`: `sum(i..=i)`. - **cost**: O(log |D|) - **traps**: when `i` is outside `D` Examples: - `Fenwick([1, 2, 3]).get(1) == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/fenwick.cp#L114) ### `Fenwick.set` ```cp fn set(mut self, i: D, x: T) ``` Assign `a[i] = x`, by adding the difference `x - get(i)`; also the write-through place for `f[i] = x`. - **cost**: O(log |D|) - **traps**: when `i` is outside `D` Examples: - `var f = Fenwick([1, 2, 3]); f.set(1, 5); f.all == 9` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/fenwick.cp#L123) ### `Fenwick.all` ```cp fn all(self) -> T ``` The sum of every position of `D`, kept current by `add`, `set` and `clear`. - **cost**: O(1) - **empty**: zero on an empty domain - **traps**: never Examples: - `Fenwick([1, 2, 3]).all == 6` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/fenwick.cp#L132) ### `Fenwick.suffix` ```cp fn suffix(self, b: Cut) -> T ``` The sum of every position right of the boundary `b`: `all - prefix(b)`. The end cut gives zero. - **cost**: O(log |D|) - **traps**: never Examples: - `Fenwick([1, 2, 3]).suffix((0..1).r) == 5` - `Fenwick([1, 2, 3]).suffix((0..3).r) == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/fenwick.cp#L141) ### `Fenwick.first_gt` ```cp fn first_gt(self, target: Int) -> ?Cut ``` The smallest boundary `b` with `prefix(b) > target`, or `None` when the whole sum is at most `target`. For non-negative values. - **cost**: O(log |D|) - **ties**: the leftmost qualifying cut - **traps**: never (negative values give an unspecified cut, not a trap) Examples: - `Fenwick([1, 2, 3]).first_gt(3) == Some((0..3).r)` - `Fenwick([1, 2, 3]).first_gt(6) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/fenwick.cp#L152) ### `Fenwick.clear` ```cp fn clear(mut self) ``` Reset every value to zero, keeping the domain and the allocation. - **cost**: O(|D|) - **traps**: never Examples: - `var f = Fenwick([1, 2, 3]); f.clear(); f.all == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/fenwick.cp#L171) ## `Fenwick2D` ```cp pub struct Fenwick2D ``` Point add and rectangle sum on a grid. `add` and `sum` are O(log R * log C); memory is (R + 1) * (C + 1) values. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/fenwick.cp#L176) ### `Fenwick2D.new` ```cp fn new() -> Fenwick2D ``` An all-zero 2-D Fenwick tree over the grid `R` by `C`. - **cost**: O(|R| |C|) time; memory (|R| + 1)(|C| + 1) values - **traps**: never Examples: - `Fenwick2D<0..2, 0..2, Int>().fold(0..2, 0..2) == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/fenwick.cp#L184) ### `Fenwick2D.add` ```cp fn add(mut self, r: R, c: C, x: T) ``` Add `x` to the cell `(r, c)`: `a[r, c] += x`. - **cost**: O(log |R| log |C|) - **traps**: when `r` is outside `R` or `c` is outside `C` Examples: - `var f = Fenwick2D<0..2, 0..2, Int>(); f.add(1, 0, 5); f.fold(1..2, 0..1) == 5` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/fenwick.cp#L191) ### `Fenwick2D.corner` ```cp fn corner(self, r: Int, c: Int) -> T ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/fenwick.cp#L200) ### `Fenwick2D.fold` ```cp fn fold(self, rows: Range, cols: Range) -> T ``` The sum over the rectangle `rows` by `cols`, by inclusion-exclusion over four prefixes. - **cost**: O(log |R| log |C|) - **empty**: zero when either range is empty - **traps**: when a range of a non-empty rectangle reaches outside its domain Examples: - `var f = Fenwick2D<0..2, 0..2, Int>(); f.add(0, 0, 1); f.add(1, 1, 2); f.fold(0..2, 1..2) == 2` - `var f = Fenwick2D<0..2, 0..2, Int>(); f.add(0, 0, 1); f.fold(0..2, 1..1) == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/fenwick.cp#L218) ### `Fenwick2D.prefix` ```cp fn prefix(self, r: Cut, c: Cut) -> T ``` The sum of every cell above the row cut `r` and left of the column cut `c`. - **cost**: O(log |R| log |C|) - **traps**: never Examples: - `var f = Fenwick2D<0..2, 0..2, Int>(); f.add(0, 0, 1); f.add(1, 1, 2); f.prefix((0..1).r, (0..2).r) == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/fenwick.cp#L230) ### `Fenwick2D.get` ```cp fn get(self, r: R, c: C) -> T ``` The current value of the cell `(r, c)`. - **cost**: O(log |R| log |C|) - **traps**: when `r` is outside `R` or `c` is outside `C` Examples: - `var f = Fenwick2D<0..2, 0..2, Int>(); f.add(1, 1, 2); f.get(1, 1) == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/fenwick.cp#L238) ### `Fenwick2D.clear` ```cp fn clear(mut self) ``` Reset every cell to zero, keeping the domains and the allocation. - **cost**: O(|R| |C|) - **traps**: never Examples: - `var f = Fenwick2D<0..2, 0..2, Int>(); f.add(1, 1, 2); f.clear(); f.get(1, 1) == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/fenwick.cp#L248) ## `DualFenwick` ```cp pub struct DualFenwick ``` Range add and point get via a difference Fenwick tree. `DualFenwick()` starts at zero and `DualFenwick(a)` from an array, in O(n). `add` and `get` are O(log n); memory is n + 1 values. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/fenwick.cp#L254) ### `DualFenwick.new` ```cp fn new(a: ?[D]T = None) -> DualFenwick ``` A range-add, point-get Fenwick tree over `D`: all zeros, or holding the values of `a` when given. It stores differences, so `get(i)` is a prefix sum of them. - **cost**: O(|D|) time; memory |D| + 1 values - **empty**: an empty `D` gives a tree with no positions to read - **order**: positions keep the domain `D` (of `a`, when given) - **traps**: never Examples: - `DualFenwick([1, 2, 3]).get(2) == 3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/fenwick.cp#L265) ### `DualFenwick.add_at` ```cp fn add_at(mut self, p0: Int, x: T) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/fenwick.cp#L278) ### `DualFenwick.add` ```cp fn add(mut self, r: Range, x: T) ``` Add `x` to every position of `r`. - **cost**: O(log |D|) - **empty**: changes nothing - **traps**: when a non-empty `r` reaches outside `D` Examples: - `var d = DualFenwick([1, 2, 3]); d.add(0..2, 10); d.get(1) == 12` - `var d = DualFenwick([1, 2, 3]); d.add(0..2, 10); d.get(2) == 3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/fenwick.cp#L291) ### `DualFenwick.get` ```cp fn get(self, i: D) -> T ``` The current value at position `i`: its initial value plus every `x` added over a range containing `i`. - **cost**: O(log |D|) - **traps**: when `i` is outside `D` Examples: - `var d = DualFenwick([1, 2, 3]); d.add(1..3, 5); d.get(1) == 7` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/fenwick.cp#L303) ### `DualFenwick.clear` ```cp fn clear(mut self) ``` Reset every value to zero, keeping the domain and the allocation. - **cost**: O(|D|) - **traps**: never Examples: - `var d = DualFenwick([1, 2, 3]); d.clear(); d.get(0) == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/fenwick.cp#L316) ## `SparseFenwick2D` ```cp pub struct SparseFenwick2D ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/fenwick.cp#L331) ### `SparseFenwick2D.new` ```cp fn new() -> SparseFenwick2D ``` An empty offline 2-D Fenwick builder. Use it in two phases: register every point that will ever be updated with `add_point`, call `build` once, then use `add` and `sum`. - **cost**: O(1) - **traps**: never Examples: - `var f = SparseFenwick2D(); f.build(); f.fold(0..10, 0..10) == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/fenwick.cp#L345) ### `SparseFenwick2D.add_point` ```cp fn add_point(mut self, x: Int, y: Int) ``` Register the point `(x, y)` as a future `add` target. Registering a point twice is harmless. - **cost**: O(1) amortized - **traps**: after `build` Examples: - `var f = SparseFenwick2D(); f.add_point(5, 7); f.add_point(5, 7); f.build(); f.add(5, 7, 3); f.fold(0..10, 0..10) == 3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/fenwick.cp#L353) ### `SparseFenwick2D.build` ```cp fn build(mut self) ``` Compress the registered `x` coordinates, and per `x` bucket the `y` coordinates it can receive, and allocate the bucket trees at zero. Ends the registration phase. - **cost**: O(n log n) for `n` registered points; memory O(n log n) - **traps**: when called a second time Examples: - `var f = SparseFenwick2D(); f.add_point(1, 2); f.build(); f.fold(1..2, 2..3) == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/fenwick.cp#L363) ### `SparseFenwick2D.add` ```cp fn add(mut self, x: Int, y: Int, v: T) ``` Add `v` at the registered point `(x, y)`. - **cost**: O(log^2 n) - **traps**: before `build`, or when `(x, y)` was never registered Examples: - `var f = SparseFenwick2D(); f.add_point(1, 2); f.add_point(3, 4); f.build(); f.add(1, 2, 5); f.add(3, 4, 7); f.fold(0..2, 0..10) == 5` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/fenwick.cp#L386) ### `SparseFenwick2D.corner` ```cp fn corner(self, x: Int, y: Int) -> T ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/fenwick.cp#L400) ### `SparseFenwick2D.fold` ```cp fn fold(self, xs: Range, ys: Range) -> T ``` The total added at registered points with `x` in `xs` and `y` in `ys`. The ranges are over raw coordinates; points outside them, or never registered, contribute nothing. - **cost**: O(log^2 n) - **empty**: zero when either range is empty - **traps**: before `build` Examples: - `var f = SparseFenwick2D(); f.add_point(1, 2); f.add_point(3, 4); f.build(); f.add(1, 2, 5); f.add(3, 4, 7); f.fold(0..10, 3..5) == 7` - `var f = SparseFenwick2D(); f.add_point(1, 2); f.build(); f.add(1, 2, 5); f.fold(2..2, 0..10) == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/fenwick.cp#L419) --- # flow URL: /docs/ref/std/flow Generated from [spec/std/flow.cp](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/flow.cp) by `cpl doc --format json`. ## `Arc` ```cp pub struct Arc(id: 0..2_147_483_648) ``` A handle to one arc of a `FlowGraph`. Handles from `add` stay valid as arcs are added. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/flow.cp#L12) ### `Arc.rev` ```cp fn rev(self) -> Arc ``` The paired arc in the opposite direction, what `e ^ 1` means in C++. Every `add` makes an arc and its reverse together, so `a.rev.rev == a`. - **cost**: O(1) - **traps**: never Examples: - `var g = FlowGraph<0..2>(); let a = g.add(0, 1, Some(5)); g.source(a.rev) == 1 and a.rev.rev == a` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/flow.cp#L19) ## `FlowGraph` ```cp pub struct FlowGraph ``` A flow network over the vertices `V`, solved with Dinic's algorithm (`max_flow`) or push-relabel (`push_relabel`). `add` is O(1). `max_flow` is O(V^2 E) in general, O(E sqrt(V)) on unit networks (bipartite matching). Memory is two arcs per `add`. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/flow.cp#L24) ### `FlowGraph.new` ```cp fn new() -> FlowGraph ``` An empty flow network over the vertices `V`. - **cost**: O(n) for n = `V.count` - **traps**: never Examples: - `let g = FlowGraph<0..3>(); g.arcs.collect() == []` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/flow.cp#L36) ### `FlowGraph.add` ```cp fn add(mut self, u: V, v: V, cap: ?Int) -> Arc ``` Adds an arc `u -> v` with capacity `cap`, and its reverse `v -> u` with capacity 0, and returns the forward arc. A `cap` of `None` is an arc no cut can afford: capacity 2^60. Self-loops are allowed and never carry flow. - **cost**: O(1) amortized; two arcs of memory - **traps**: when `cap` is negative Examples: - `var g = FlowGraph<0..2>(); let a = g.add(0, 1, Some(5)); g.cap(a) == 5 and g.cap(a.rev) == 0` - `var g = FlowGraph<0..2>(); let a = g.add(0, 1, None); g.cap(a) == 1 << 60` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/flow.cp#L47) ### `FlowGraph.add_both` ```cp fn add_both(mut self, u: V, v: V, cap: Int) -> Arc ``` Adds an undirected edge between `u` and `v`: an arc `u -> v` whose reverse also has capacity `cap`. Returns the `u -> v` arc. - **cost**: O(1) amortized; two arcs of memory - **traps**: when `cap` is negative Examples: - `var g = FlowGraph<0..2>(); let a = g.add_both(0, 1, 3); g.cap(a.rev) == 3 and g.max_flow(1, 0) == 3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/flow.cp#L68) ### `FlowGraph.flow` ```cp fn flow(self, a: Arc) -> Int ``` The flow currently sent along `a`: negative on the reverse arc of a used arc, so `flow(a.rev) == -flow(a)`. - **cost**: O(1) - **traps**: never Examples: - `var g = FlowGraph<0..2>(); let a = g.add(0, 1, Some(5)); g.max_flow(0, 1); g.flow(a) == 5 and g.flow(a.rev) == -5` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/flow.cp#L80) ### `FlowGraph.cap` ```cp fn cap(self, a: Arc) -> Int ``` The capacity `a` has now: what `add` or the last `set_cap` gave it, 0 for the reverse arc of an `add`, `cap` for either arc of an `add_both`. - **cost**: O(1) - **traps**: never Examples: - `var g = FlowGraph<0..2>(); let a = g.add(0, 1, Some(4)); g.cap(a) == 4` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/flow.cp#L88) ### `FlowGraph.source` ```cp fn source(self, a: Arc) -> V ``` The vertex `a` leaves. - **cost**: O(1) - **traps**: never Examples: - `var g = FlowGraph<0..3>(); let a = g.add(2, 0, Some(1)); g.source(a) == 2 and g.source(a.rev) == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/flow.cp#L95) ### `FlowGraph.target` ```cp fn target(self, a: Arc) -> V ``` The vertex `a` points to. - **cost**: O(1) - **traps**: never Examples: - `var g = FlowGraph<0..3>(); let a = g.add(2, 0, Some(1)); g.target(a) == 0 and g.target(a.rev) == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/flow.cp#L102) ### `FlowGraph.max_flow` ```cp fn max_flow(mut self, s: V, t: V, limit: ?Int = None) -> Int ``` Pushes as much flow as possible from `s` to `t`, on top of the flow already there but no more than `limit` in this call, and returns the amount added. Dinic's algorithm: BFS levels, then blocking flows by DFS scanning each vertex's arcs in `add` order. Calling it again with no change adds 0; after it runs to completion (returns less than `limit`, or `limit` is `None`), `min_cut(s)` and `cut_arcs(s)` are valid. - **cost**: O(V² E); O(E sqrt V) when every capacity is 1 - **ties**: among maximum flows, the one Dinic finds scanning arcs in `add` order - **traps**: when `s == t` or `limit` is negative Examples: - `var g = FlowGraph<0..4>(); g.add(0, 1, Some(3)); g.add(0, 2, Some(2)); g.add(1, 2, Some(1)); g.add(1, 3, Some(2)); g.add(2, 3, Some(3)); g.max_flow(0, 3) == 5` - `var g = FlowGraph<0..4>(); g.add(0, 1, Some(3)); g.add(0, 2, Some(2)); g.add(1, 2, Some(1)); g.add(1, 3, Some(2)); g.add(2, 3, Some(3)); g.max_flow(0, 3, limit: Some(4)) == 4 and g.max_flow(0, 3) == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/flow.cp#L116) ### `FlowGraph.min_cut` ```cp fn min_cut(self, s: V) -> [V]Bool ``` The source side of a minimum `s`-`t` cut: the vertices `s` still reaches in the residual network, after `max_flow(s, t)` (or `push_relabel(s, t)`) ran to completion. - **cost**: O(V + E) - **ties**: the smallest source side among minimum cuts (exactly what `s` reaches) - **order**: keyed by `V` - **traps**: when no completed `max_flow` or `push_relabel` from `s` came since the last `add`, `set_cap` or `reset` Examples: - `var g = FlowGraph<0..3>(); g.add(0, 1, Some(5)); g.add(1, 2, Some(1)); g.max_flow(0, 2); g.min_cut(0) == [true, true, false]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/flow.cp#L141) ### `FlowGraph.reset` ```cp fn reset(mut self) ``` Clears all flow, so every arc is back at its current capacity with nothing sent. - **cost**: O(E) - **traps**: never Examples: - `var g = FlowGraph<0..2>(); let a = g.add(0, 1, Some(5)); g.max_flow(0, 1); g.reset(); g.flow(a) == 0 and g.max_flow(0, 1) == 5` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/flow.cp#L151) ### `FlowGraph.set_cap` ```cp fn set_cap(mut self, a: Arc, cap: ?Int) ``` Changes arc `a`'s capacity to `cap` (`None`: 2^60), keeping its flow; a later `max_flow` continues from the current flow. The reverse arc keeps its own capacity. - **cost**: O(1) - **traps**: when the flow on `a` exceeds the new capacity (lower it with `reset` first), or `cap` is negative Examples: - `var g = FlowGraph<0..2>(); let a = g.add(0, 1, Some(2)); g.max_flow(0, 1); g.set_cap(a, Some(5)); g.max_flow(0, 1) == 3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/flow.cp#L161) ### `FlowGraph.residual` ```cp fn residual(self, a: Arc) -> Int ``` The capacity left on `a` in the residual network: `cap(a) - flow(a)`. - **cost**: O(1) - **traps**: never Examples: - `var g = FlowGraph<0..2>(); let a = g.add(0, 1, Some(5)); g.max_flow(0, 1, limit: Some(2)); g.residual(a) == 3 and g.residual(a.rev) == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/flow.cp#L174) ### `FlowGraph.arcs` ```cp fn arcs(self) -> yields Arc ``` Every arc `add` or `add_both` returned, lazily; never a reverse arc. O(1) to make. - **cost**: O(E) for the whole walk - **empty**: yields nothing before the first `add` - **order**: the order `add` returned them - **traps**: never Examples: - `var g = FlowGraph<0..3>(); let a = g.add(0, 1, Some(1)); let b = g.add(1, 2, Some(1)); g.arcs.collect() == [a, b]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/flow.cp#L183) ### `FlowGraph.out` ```cp fn out(self, u: V) -> yields Arc ``` The arcs `add` or `add_both` returned whose source is `u`, lazily; never a reverse arc. - **cost**: O(deg u) for the whole walk - **empty**: yields nothing when no added arc leaves `u` - **order**: the order `add` returned them - **traps**: never Examples: - `var g = FlowGraph<0..3>(); let a = g.add(0, 1, Some(1)); g.add(1, 2, Some(1)); let c = g.add(0, 2, Some(1)); g.out(0).collect() == [a, c]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/flow.cp#L193) ### `FlowGraph.cut_arcs` ```cp fn cut_arcs(self, s: V) -> List ``` The added arcs crossing the minimum cut `min_cut(s)` from the source side to the other, after `max_flow(s, t)` ran to completion. Every one is saturated and their capacities sum to the flow value. - **cost**: O(V + E) - **order**: the order `add` returned them - **traps**: like `min_cut`, when the flow from `s` is missing or stale Examples: - `var g = FlowGraph<0..3>(); g.add(0, 1, Some(5)); let b = g.add(1, 2, Some(1)); g.max_flow(0, 2); g.cut_arcs(0) == [b]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/flow.cp#L205) ### `FlowGraph.paths` ```cp fn paths(self, s: V, t: V) -> yields (arcs: List, amount: Int) ``` The current `s`-`t` flow split into paths, each with the amount it carries; the amounts sum to the net flow out of `s`. Cycles of flow are skipped. Does not change the flow. Each path walks from `s` along the first arc, in `add` order, that still carries unclaimed flow, until it reaches `t`; its amount is the least unclaimed flow on the way. - **cost**: O(P (V + E)) for P paths - **empty**: yields nothing when no flow goes from `s` to `t` - **order**: discovery order, as above - **traps**: when `s == t` Examples: - `var g = FlowGraph<0..4>(); let a = g.add(0, 1, Some(1)); let b = g.add(1, 3, Some(1)); let c = g.add(0, 2, Some(1)); let d = g.add(2, 3, Some(1)); g.max_flow(0, 3); g.paths(0, 3).collect() == [(arcs: [a, b], amount: 1), (arcs: [c, d], amount: 1)]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/flow.cp#L220) ### `FlowGraph.push_relabel` ```cp fn push_relabel(mut self, s: V, t: V) -> Int ``` The same maximum flow amount as `max_flow(s, t)` by push-relabel (highest label, gap heuristic), often several times faster than Dinic on dense or unit-capacity grids. Adds to the flow already there and returns the amount added; `min_cut(s)` works after it. - **cost**: O(V² sqrt E) - **traps**: when `s == t` Examples: - `var g = FlowGraph<0..4>(); g.add(0, 1, Some(3)); g.add(0, 2, Some(2)); g.add(1, 2, Some(1)); g.add(1, 3, Some(2)); g.add(2, 3, Some(3)); g.push_relabel(0, 3) == 5` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/flow.cp#L262) ### `FlowGraph.push` ```cp fn push( mut self, a: Arc, f: Int, mut excess: [V]Int, mut active: List>, height: [V]Int, ) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/flow.cp#L307) ### `FlowGraph.close` ```cp fn close(mut self, a: Arc) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/flow.cp#L323) ### `FlowGraph.levels` ```cp fn levels(self, s: V) -> [V]?Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/flow.cp#L327) ### `FlowGraph.augment` ```cp fn augment(mut self, s: V, t: V, level: [V]?Int, mut next: [V]Int, most: Int) -> Int ``` One augmenting path in the level graph, found without recursion. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/flow.cp#L344) ## `CostFlow` ```cp pub struct CostFlow ``` A flow network with a cost per unit on every arc, solved by successive shortest paths with Johnson potentials. Arc handles and accessors are those of `FlowGraph`. `add` is O(1); memory is two arcs per `add`. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/flow.cp#L371) ### `CostFlow.new` ```cp fn new() -> CostFlow ``` An empty min-cost flow network over the vertices `V`. - **cost**: O(n) for n = `V.count` - **traps**: never Examples: - `let g = CostFlow<0..3>(); g.arcs.collect() == []` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/flow.cp#L383) ### `CostFlow.add` ```cp fn add(mut self, u: V, v: V, cap: ?Int, cost: Int) -> Arc ``` Adds an arc `u -> v` with capacity `cap` and cost `cost` per unit; its reverse has capacity 0 and cost `-cost`. `cap: None` is 2^60. Costs may be negative; `min_cost_flow` needs no residual cycle of negative total cost (run `cancel_cycles` first when there may be one). - **cost**: O(1) amortized; two arcs of memory - **traps**: when `cap` is negative Examples: - `var g = CostFlow<0..2>(); let a = g.add(0, 1, Some(2), 7); g.cost(a) == 7 and g.cost(a.rev) == -7` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/flow.cp#L393) ### `CostFlow.flow` ```cp fn flow(self, a: Arc) -> Int ``` The flow currently sent along `a`; `flow(a.rev) == -flow(a)`. - **cost**: O(1) - **traps**: never Examples: - `var g = CostFlow<0..2>(); let a = g.add(0, 1, Some(2), 1); g.min_cost_flow(0, 1); g.flow(a) == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/flow.cp#L414) ### `CostFlow.cap` ```cp fn cap(self, a: Arc) -> Int ``` The capacity `a` has now: what `add` or the last `set_cap` gave it, 0 for a reverse arc. - **cost**: O(1) - **traps**: never Examples: - `var g = CostFlow<0..2>(); let a = g.add(0, 1, Some(2), 1); g.cap(a) == 2 and g.cap(a.rev) == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/flow.cp#L421) ### `CostFlow.cost` ```cp fn cost(self, a: Arc) -> Int ``` The cost per unit of flow along `a`; `cost(a.rev) == -cost(a)`. - **cost**: O(1) - **traps**: never Examples: - `var g = CostFlow<0..2>(); let a = g.add(0, 1, Some(2), -3); g.cost(a) == -3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/flow.cp#L428) ### `CostFlow.source` ```cp fn source(self, a: Arc) -> V ``` The vertex `a` leaves. - **cost**: O(1) - **traps**: never Examples: - `var g = CostFlow<0..3>(); let a = g.add(2, 0, Some(1), 0); g.source(a) == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/flow.cp#L435) ### `CostFlow.target` ```cp fn target(self, a: Arc) -> V ``` The vertex `a` points to. - **cost**: O(1) - **traps**: never Examples: - `var g = CostFlow<0..3>(); let a = g.add(2, 0, Some(1), 0); g.target(a) == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/flow.cp#L442) ### `CostFlow.set_cap` ```cp fn set_cap(mut self, a: Arc, cap: ?Int) ``` Changes arc `a`'s capacity, keeping its flow, as [`FlowGraph.set_cap`](FlowGraph.set_cap). - **cost**: O(1) - **traps**: when the flow on `a` exceeds the new capacity, or `cap` is negative Examples: - `var g = CostFlow<0..2>(); let a = g.add(0, 1, Some(1), 2); g.min_cost_flow(0, 1); g.set_cap(a, Some(3)); g.min_cost_flow(0, 1) == (flow: 2, cost: 4)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/flow.cp#L449) ### `CostFlow.arcs` ```cp fn arcs(self) -> yields Arc ``` Every arc `add` returned, lazily; never a reverse arc. O(1) to make. - **cost**: O(E) for the whole walk - **empty**: yields nothing before the first `add` - **order**: the order `add` returned them - **traps**: never Examples: - `var g = CostFlow<0..2>(); let a = g.add(0, 1, Some(1), 0); let b = g.add(1, 0, Some(1), 0); g.arcs.collect() == [a, b]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/flow.cp#L463) ### `CostFlow.cancel_cycles` ```cp fn cancel_cycles(mut self) -> Int ``` Saturates every negative-cost cycle of the residual network, so the stored flow becomes a min-cost circulation plus the `s`-`t` flows already sent, and returns the cost added (zero or negative). Negative cycles are allowed here; afterwards `min_cost_flow` is safe. - **cost**: O(V E log V) worst case, by cost scaling - **traps**: never Examples: - `var g = CostFlow<0..2>(); g.add(0, 1, Some(1), -2); g.add(1, 0, Some(1), 1); g.cancel_cycles() == -1` - `var g = CostFlow<0..2>(); g.add(0, 1, Some(1), 2); g.cancel_cycles() == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/flow.cp#L475) ### `CostFlow.min_cost_flow` ```cp fn min_cost_flow(mut self, s: V, t: V, limit: ?Int = None) -> (flow: Int, cost: Int) ``` Sends the most flow from `s` to `t`, up to `limit` in this call, at the least cost among flows of that amount, on top of the flow already there. Returns the amount and cost added. Successive shortest paths with Johnson potentials: each augmentation takes a cheapest residual path, so the cost added is convex in the amount (see `slope`). Costs may be negative; the first call with a negative residual arc runs Bellman-Ford once. - **cost**: O(F E log V) for F augmenting paths, plus O(V E) once when a residual arc has a negative cost - **ties**: among cheapest flows, the one the shortest paths find (Dijkstra breaking ties by least vertex) - **traps**: when `s == t`, `limit` is negative, or the residual network has a negative-cost cycle Examples: - `var g = CostFlow<0..3>(); g.add(0, 1, Some(2), 1); g.add(1, 2, Some(2), 1); g.add(0, 2, Some(1), 5); g.min_cost_flow(0, 2) == (flow: 3, cost: 9)` - `var g = CostFlow<0..3>(); g.add(0, 1, Some(2), 1); g.add(1, 2, Some(2), 1); g.add(0, 2, Some(1), 5); g.min_cost_flow(0, 2, limit: Some(2)) == (flow: 2, cost: 4)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/flow.cp#L529) ### `CostFlow.slope` ```cp fn slope(mut self, s: V, t: V, limit: ?Int = None) -> List<(flow: Int, cost: Int)> ``` The breakpoints of the cheapest cost of sending each amount from `s` to `t`, up to `limit`: `(0, 0)` first, then one `(flow, cost)` per change of slope, ending at the largest amount. Between breakpoints the cost is linear and the slopes never decrease. Sends the flow, as `min_cost_flow` does; amounts and costs are relative to the flow already there. - **cost**: as `min_cost_flow` - **order**: increasing `flow` - **traps**: as `min_cost_flow` Examples: - `var g = CostFlow<0..3>(); g.add(0, 1, Some(2), 1); g.add(1, 2, Some(2), 1); g.add(0, 2, Some(1), 5); g.slope(0, 2) == [(flow: 0, cost: 0), (flow: 2, cost: 4), (flow: 3, cost: 9)]` - `var g = CostFlow<0..2>(); g.slope(0, 1) == [(flow: 0, cost: 0)]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/flow.cp#L543) ### `CostFlow.potentials` ```cp fn potentials(self) -> [V]Int ``` Potentials under which every residual arc has a nonnegative reduced cost: all zero when no residual arc is negative, else Bellman-Ford from every vertex at once. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/flow.cp#L597) ## `Matching` ```cp pub struct Matching ``` O(E sqrt V) for the first `augment_all`, O(V + E) per later `add` + `augment`. A bipartite matching that grows with the graph: edges arrive online and each `augment(l)` tries one augmenting path from `l` (Kuhn), so a contest that adds vertices or edges between queries keeps a maximum matching without re-solving. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/flow.cp#L1553) ### `Matching.new` ```cp fn new() -> Matching ``` An online bipartite matching between `L` and `R` with no edges and nothing matched. - **cost**: O(L + R) - **traps**: never Examples: - `let m = Matching<0..2, 0..2>(); m.len == 0 and m.mate(0) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/flow.cp#L1564) ### `Matching.add` ```cp fn add(mut self, l: L, r: R) ``` Allows `l` to match `r`. Does not augment; a repeated edge is harmless. - **cost**: O(1) amortized - **traps**: never Examples: - `var m = Matching<0..2, 0..2>(); m.add(0, 1); m.len == 0 and m.augment(0) and m.mate(0) == Some(1)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/flow.cp#L1575) ### `Matching.augment` ```cp fn augment(mut self, from: L) -> Bool ``` Looks for one augmenting path from the unmatched `from` (Kuhn's DFS, trying edges in `add` order); `true` when it grew the matching. `false` also when `from` is already matched. - **cost**: O(V + E) - **traps**: never Examples: - `var m = Matching<0..2, 0..2>(); m.add(0, 0); m.add(0, 1); m.add(1, 0); m.augment(0); m.augment(1) and m.mate(0) == Some(1) and m.mate(1) == Some(0)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/flow.cp#L1583) ### `Matching.augment_all` ```cp fn augment_all(mut self) -> Int ``` Grows the current matching to a maximum one by Hopcroft-Karp and returns the number of pairs added. - **cost**: O(E sqrt V) - **traps**: never Examples: - `var m = Matching<0..2, 0..2>(); m.add(0, 0); m.add(1, 0); m.add(1, 1); m.augment_all() == 2 and m.len == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/flow.cp#L1612) ### `Matching.remove` ```cp fn remove(mut self, l: L) -> Int ``` Unmatches `l` and its mate `r`, then tries to rematch both: `augment(l)` first, then one augmenting path ending at `r` if it is still free. Returns the new size; the matching stays maximum when it was before. No edge is removed. - **cost**: O(V + E) - **traps**: never Examples: - `var m = Matching<0..2, 0..2>(); m.add(0, 0); m.add(1, 0); m.augment(0); m.remove(0) == 1 and m.mate(0) == Some(0)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/flow.cp#L1624) ### `Matching.mate` ```cp fn mate(self, l: L) -> ?R ``` `l`'s partner, `None` when unmatched. - **cost**: O(1) - **traps**: never Examples: - `var m = Matching<0..2, 0..2>(); m.add(1, 0); m.augment(1); m.mate(1) == Some(0) and m.mate(0) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/flow.cp#L1668) ### `Matching.back` ```cp fn back(self, r: R) -> ?L ``` `r`'s partner, `None` when unmatched. - **cost**: O(1) - **traps**: never Examples: - `var m = Matching<0..2, 0..2>(); m.add(1, 0); m.augment(1); m.back(0) == Some(1) and m.back(1) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/flow.cp#L1674) ### `Matching.len` ```cp fn len(self) -> Int ``` The number of matched pairs. - **cost**: O(1) - **traps**: never Examples: - `var m = Matching<0..2, 0..2>(); m.add(1, 0); m.augment(1); m.len == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/flow.cp#L1680) ### `Matching.cover` ```cp fn cover(self) -> (left: [L]Bool, right: [R]Bool) ``` The König vertex cover of the current matching, built as in [`min_vertex_cover`](min_vertex_cover); a minimum cover when the matching is maximum. - **cost**: O(V + E) - **order**: `left` keyed by `L`, `right` keyed by `R` - **traps**: never Examples: - `var m = Matching<0..2, 0..1>(); m.add(0, 0); m.add(1, 0); m.augment_all(); m.cover() == (left: [false, false], right: [true])` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/flow.cp#L1688) ## `Matroid` ```cp pub trait Matroid ``` An independence oracle for `matroid_intersection`. `rebuild(take)` sets the current independent set; `can_add(e)` asks whether `take + e` stays independent, and `can_swap(out, e)` whether `take - out + e` does. Graphic and colour (partition) matroids ship as `GraphicMatroid` and `ColorMatroid`. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/flow.cp#L1754) ### `Matroid.rebuild` ```cp fn rebuild(mut self, take: [E]Bool) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/flow.cp#L1755) ### `Matroid.can_add` ```cp fn can_add(self, e: E) -> Bool ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/flow.cp#L1756) ### `Matroid.can_swap` ```cp fn can_swap(self, out: E, e: E) -> Bool ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/flow.cp#L1757) ## `GraphicMatroid` ```cp pub struct GraphicMatroid ``` O(E α) per rebuild. Independent sets are forests of the edges' endpoints. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/flow.cp#L1760) ### `GraphicMatroid.new` ```cp fn new(edges: [E](u: V, v: V)) -> GraphicMatroid ``` The graphic matroid of `edges`: a set of edges is independent when it is a forest on `V`. - **cost**: O(1); each `rebuild` is O(E alpha(V)) - **traps**: never Examples: - `let es: [0..3](u: 0..3, v: 0..3) = [(u: 0, v: 1), (u: 1, v: 2), (u: 0, v: 2)]; var m = GraphicMatroid(es); m.rebuild([true, true, false]); not m.can_add(2) and m.can_swap(0, 2)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/flow.cp#L1767) ## `ColorMatroid` ```cp pub struct ColorMatroid ``` O(E) per rebuild. Independent sets take at most `limit[c]` elements of each colour. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/flow.cp#L1770) ### `ColorMatroid.new` ```cp fn new(color: [E]C, limit: [C]Int) -> ColorMatroid ``` The partition matroid of `color`: a set is independent when it holds at most `limit[c]` elements of each colour `c`. - **cost**: O(1); each `rebuild` is O(E) - **empty**: with no elements only the empty set exists and every query is `false` - **traps**: when some `limit[c]` is negative Examples: - `let col: [0..3]0..2 = [0, 0, 1]; let lim: [0..2]Int = [1, 1]; var m = ColorMatroid(col, lim); m.rebuild([true, false, false]); not m.can_add(1) and m.can_add(2)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/flow.cp#L1780) --- # geometry URL: /docs/ref/std/geometry Generated from [spec/std/geometry.cp](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp) by `cpl doc --format json`. ## `Pt` ```cp pub struct Pt(x: Int, y: Int) ``` O(1) value type. A 2D point or vector with exact integer coordinates. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L25) ### `Pt.norm2` ```cp fn norm2(self) -> Int ``` The squared length `x*x + y*y`, in `Int`. Fits for `|x|, |y| <= 2e9`; use `norm2_128` beyond. - **cost**: O(1) - **traps**: when the result overflows `Int` Examples: - `Pt(3, 4).norm2 == 25` - `Pt(0, 0).norm2 == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L34) ### `Pt.norm2_128` ```cp fn norm2_128(self) -> I128 ``` The exact squared length `x*x + y*y`, computed in `I128`. - **cost**: O(1) - **traps**: when the result overflows `I128` (only for coordinates near `Int.MIN`) Examples: - `Pt(3, 4).norm2_128 == 25` - `Pt(3_000_000_000, 4_000_000_000).norm2_128 == 25_000_000_000_000_000_000` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L42) ### `Pt.len` ```cp fn len(self) -> F64 ``` The Euclidean length `sqrt(x*x + y*y)` as `F64` (`hypot`, so no intermediate overflow). - **cost**: O(1) - **traps**: never Examples: - `Pt(3, 4).len == 5.0` - `Pt(0, 0).len == 0.0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L50) ### `Pt.perp` ```cp fn perp(self) -> Pt ``` `self` rotated 90 degrees counter-clockwise: `Pt(-y, x)`. - **cost**: O(1) - **traps**: when `y` is `Int.MIN` Examples: - `Pt(1, 2).perp == Pt(-2, 1)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L57) ### `Pt.perp_cw` ```cp fn perp_cw(self) -> Pt ``` `self` rotated 90 degrees clockwise: `Pt(y, -x)`. - **cost**: O(1) - **traps**: when `x` is `Int.MIN` Examples: - `Pt(1, 2).perp_cw == Pt(2, -1)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L64) ### `Pt.angle` ```cp fn angle(self) -> F64 ``` The polar angle `atan2(y, x)` in `(-pi, pi]`; 0 for the zero vector. For exact angular comparisons use `arg` or `angle_less` instead. - **cost**: O(1) - **traps**: never Examples: - `Pt(1, 0).angle == 0.0` - `Pt(0, -1).angle < 0.0` - `Pt(-1, 0).angle > 3.14` - `Pt(0, 0).angle == 0.0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L76) ### `Pt.unit_dir` ```cp fn unit_dir(self) -> Pt ``` The reduced integer direction `(x / g, y / g)` with `g = gcd(|x|, |y|)`; `Pt(0, 0)` for the zero vector. Two nonzero vectors point the same way exactly when their `unit_dir`s are equal, so it is a hashable direction key. - **cost**: O(log max(|x|, |y|)) - **traps**: never Examples: - `Pt(4, -6).unit_dir() == Pt(2, -3)` - `Pt(0, 5).unit_dir() == Pt(0, 1)` - `Pt(0, 0).unit_dir() == Pt(0, 0)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L89) ### `Pt.to_vec` ```cp fn to_vec(self) -> Vec ``` `self` as a floating-point `Vec(F64(x), F64(y))`: the explicit way across. - **cost**: O(1) - **traps**: never Examples: - `Pt(1, 2).to_vec == Vec(1.0, 2.0)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L99) ### `Pt.dot` ```cp fn dot(self, o: Pt) -> Int ``` The dot product `x * o.x + y * o.y`, in `Int`. - **cost**: O(1) - **traps**: when the result or a product overflows `Int` Examples: - `Pt(1, 2).dot(Pt(3, 4)) == 11` - `Pt(1, 0).dot(Pt(0, 1)) == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L107) ### `Pt.dot128` ```cp fn dot128(self, o: Pt) -> I128 ``` The exact dot product `x * o.x + y * o.y`, computed in `I128`. - **cost**: O(1) - **traps**: when the sum overflows `I128` (only when every coordinate is near `Int.MIN`) Examples: - `Pt(1, 2).dot128(Pt(3, 4)) == 11` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L114) ### `Pt.cross` ```cp fn cross(self, o: Pt) -> Int ``` The 2D cross product `x * o.y - y * o.x`, in `Int`: positive when `o` is counter-clockwise from `self`, negative when clockwise, 0 when parallel. - **cost**: O(1) - **traps**: when the result or a product overflows `Int` Examples: - `Pt(1, 0).cross(Pt(0, 1)) == 1` - `Pt(1, 2).cross(Pt(3, 4)) == -2` - `Pt(1, 2).cross(Pt(2, 4)) == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L124) ### `Pt.cross128` ```cp fn cross128(self, o: Pt) -> I128 ``` The exact 2D cross product `x * o.y - y * o.x`, computed in `I128`. - **cost**: O(1) - **traps**: when the difference overflows `I128` (only for coordinates near `Int.MIN`) Examples: - `Pt(1, 2).cross128(Pt(3, 4)) == -2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L131) ### `Pt.dist2` ```cp fn dist2(self, o: Pt) -> Int ``` The squared Euclidean distance from `self` to `o`, in `Int`. - **cost**: O(1) - **traps**: when the result overflows `Int` Examples: - `Pt(0, 0).dist2(Pt(3, 4)) == 25` - `Pt(1, 1).dist2(Pt(1, 1)) == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L139) ### `Pt.dist2_128` ```cp fn dist2_128(self, o: Pt) -> I128 ``` The exact squared Euclidean distance from `self` to `o`, computed in `I128`. - **cost**: O(1) - **traps**: when the result overflows `I128` (coordinates beyond about `4e18` apart) Examples: - `Pt(0, 0).dist2_128(Pt(3, 4)) == 25` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L146) ### `Pt.dist` ```cp fn dist(self, o: Pt) -> F64 ``` The Euclidean distance from `self` to `o`, as `F64`. - **cost**: O(1) - **traps**: never Examples: - `Pt(0, 0).dist(Pt(3, 4)) == 5.0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L153) ### `Pt.manhattan` ```cp fn manhattan(self, o: Pt) -> Int ``` The Manhattan (L1) distance `|x - o.x| + |y - o.y|`. - **cost**: O(1) - **traps**: when the result overflows `Int` Examples: - `Pt(1, 1).manhattan(Pt(4, -3)) == 7` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L160) ### `Pt.chebyshev` ```cp fn chebyshev(self, o: Pt) -> Int ``` The Chebyshev (L-infinity) distance `max(|x - o.x|, |y - o.y|)`. - **cost**: O(1) - **traps**: when the result overflows `Int` Examples: - `Pt(1, 1).chebyshev(Pt(4, -3)) == 4` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L167) ## `Pt` ```cp impl Add for Pt ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L169) ### `Pt.add` ```cp fn add(a, b) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L170) ## `Pt` ```cp impl Sub for Pt ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L172) ### `Pt.sub` ```cp fn sub(a, b) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L173) ## `Pt` ```cp impl Neg for Pt ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L175) ### `Pt.neg` ```cp fn neg(a) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L176) ## `Pt` ```cp impl Mul for Pt ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L178) ### `Pt.mul` ```cp fn mul(a, k) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L179) ## `Pt` ```cp impl Show for Pt ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L181) ### `Pt.show` ```cp fn show(a) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L182) ## `ByAngle` ```cp pub struct ByAngle(p ``` O(1) comparison key. Counter-clockwise by direction, starting from the positive x axis. Exact in `I128`; vectors in the same direction compare equal, zero comes first. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L248) ## `ByAngle` ```cp impl Ord for ByAngle ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L250) ### `ByAngle.lt` ```cp fn lt(a, b) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L251) ## `ByAngleFrom` ```cp pub struct ByAngleFrom(base: Pt, p ``` O(1) comparison key. Counter-clockwise by direction starting from ray `base`. Exact in `I128`; vectors in the same direction compare equal, zero comes first. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L255) ## `ByAngleFrom` ```cp impl Ord for ByAngleFrom ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L257) ### `ByAngleFrom.lt` ```cp fn lt(a, b) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L258) ## `OnlineHull` ```cp pub struct OnlineHull ``` O(n) memory. Incremental 2D convex hull of integer points backed by upper and lower chains. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L484) ### `OnlineHull.new` ```cp fn new() -> OnlineHull ``` An empty online convex hull. The hull keeps strict corners only: points on an edge or inside are absorbed. - **cost**: O(1) - **traps**: never Examples: - `OnlineHull().is_empty == true` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L495) ### `OnlineHull.add` ```cp fn add(mut self, p: Pt) -> Bool ``` Insert `p` and report whether the hull changed (whether `p` is now a corner). A point inside, on the boundary, or equal to a corner returns false and changes nothing. - **cost**: O(log n) amortized - **traps**: never Examples: - `var h = OnlineHull(); h.add(Pt(0, 0)) == true` - `var h = OnlineHull(); h.add(Pt(0, 0)); h.add(Pt(4, 0)); h.add(Pt(0, 4)); h.add(Pt(1, 1)) == false` - `var h = OnlineHull(); h.add(Pt(0, 0)); h.add(Pt(0, 0)) == false` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L507) ### `OnlineHull.locate` ```cp fn locate(self, p: Pt) -> Location ``` Where `p` is relative to the current hull: `Inside`, `Boundary` or `Outside`. An empty hull has everything `Outside`; a one-point or segment hull has only its points on the `Boundary`. - **cost**: O(log n) - **traps**: never Examples: - `var h = OnlineHull(); h.add(Pt(0, 0)); h.add(Pt(4, 0)); h.add(Pt(0, 4)); h.locate(Pt(1, 1)) == Location.Inside` - `var h = OnlineHull(); h.add(Pt(0, 0)); h.add(Pt(4, 0)); h.add(Pt(0, 4)); h.locate(Pt(2, 0)) == Location.Boundary` - `OnlineHull().locate(Pt(0, 0)) == Location.Outside` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L530) ### `OnlineHull.extreme` ```cp fn extreme(self, dir: Pt) -> ?Pt ``` The hull corner maximizing `v.dot128(dir)`, or `None` when the hull is empty. Ties go to the corner that comes first in `vertices()` order. - **cost**: O(log n) - **ties**: the first in `vertices()` order - **traps**: never Examples: - `var h = OnlineHull(); h.add(Pt(0, 0)); h.add(Pt(4, 0)); h.add(Pt(0, 4)); h.extreme(Pt(1, 1)) == Some(Pt(4, 0))` - `var h = OnlineHull(); h.add(Pt(0, 0)); h.add(Pt(4, 0)); h.add(Pt(0, 4)); h.extreme(Pt(0, 1)) == Some(Pt(0, 4))` - `OnlineHull().extreme(Pt(1, 0)) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L561) ### `OnlineHull.area2` ```cp fn area2(self) -> Int ``` Twice the area of the current hull; 0 with fewer than 3 non-collinear points. - **cost**: O(1) - **traps**: when the value overflows `Int` Examples: - `var h = OnlineHull(); h.add(Pt(0, 0)); h.add(Pt(4, 0)); h.add(Pt(0, 4)); h.area2 == 16` - `OnlineHull().area2 == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L578) ### `OnlineHull.len` ```cp fn len(self) -> Int ``` The number of hull corners. - **cost**: O(1) - **traps**: never Examples: - `var h = OnlineHull(); h.add(Pt(0, 0)); h.add(Pt(4, 0)); h.add(Pt(0, 4)); h.add(Pt(1, 1)); h.len == 3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L585) ### `OnlineHull.is_empty` ```cp fn is_empty(self) -> Bool ``` Whether no point has been added since creation or the last `clear`. - **cost**: O(1) - **traps**: never Examples: - `OnlineHull().is_empty == true` - `var h = OnlineHull(); h.add(Pt(1, 1)); h.is_empty == false` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L593) ### `OnlineHull.vertices` ```cp fn vertices(self) -> List ``` The current hull corners, counter-clockwise from the least `(x, y)`. - **cost**: O(n) time and memory - **order**: counter-clockwise, starting at the least `(x, y)`; a new `List`, keyed from 0 - **traps**: never Examples: - `var h = OnlineHull(); h.add(Pt(0, 4)); h.add(Pt(4, 0)); h.add(Pt(0, 0)); h.vertices() == [Pt(0, 0), Pt(4, 0), Pt(0, 4)]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L601) ### `OnlineHull.iter` ```cp fn iter(self) -> yields Pt ``` The current hull corners, yielded in `vertices()` order without building a list. - **cost**: O(n) - **order**: counter-clockwise, starting at the least `(x, y)` - **traps**: never Examples: - `var h = OnlineHull(); h.add(Pt(0, 4)); h.add(Pt(4, 0)); h.add(Pt(0, 0)); h.iter().collect() == [Pt(0, 0), Pt(4, 0), Pt(0, 4)]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L609) ### `OnlineHull.clear` ```cp fn clear(mut self) ``` Remove every point; the hull is then empty. - **cost**: O(n) - **traps**: never Examples: - `var h = OnlineHull(); h.add(Pt(1, 1)); h.clear(); h.is_empty` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L617) ## `Location` ```cp pub enum Location = Inside | Boundary | Outside ``` O(1) enum. Position of a point relative to a polygon or disk. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L809) ### `Location.Inside` ```cp Inside ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L809) ### `Location.Boundary` ```cp Boundary ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L809) ### `Location.Outside` ```cp Outside ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L809) ## `PI` ```cp pub const PI: F64 = 3.14159265358979323846 ``` O(1). Circle constant pi (canonical home: `std.math.PI`; re-exported here). [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L1446) ## `Vec` ```cp pub struct Vec(x: F64, y: F64) ``` O(1) value type. A 2D floating-point point or vector. Kept distinct from `Pt` so exact integer predicates never silently mix with approximate arithmetic. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L1470) ### `Vec.norm2` ```cp fn norm2(self) -> F64 ``` The squared length `x*x + y*y`. - **cost**: O(1) - **traps**: never Examples: - `Vec(3.0, 4.0).norm2 == 25.0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L1476) ### `Vec.len` ```cp fn len(self) -> F64 ``` The Euclidean length (`hypot(x, y)`, so no intermediate overflow). - **cost**: O(1) - **traps**: never Examples: - `Vec(3.0, 4.0).len == 5.0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L1483) ### `Vec.perp` ```cp fn perp(self) -> Vec ``` `self` rotated 90 degrees counter-clockwise: `Vec(-y, x)`. - **cost**: O(1) - **traps**: never Examples: - `Vec(1.0, 2.0).perp == Vec(-2.0, 1.0)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L1490) ### `Vec.perp_cw` ```cp fn perp_cw(self) -> Vec ``` `self` rotated 90 degrees clockwise: `Vec(y, -x)`. - **cost**: O(1) - **traps**: never Examples: - `Vec(1.0, 2.0).perp_cw == Vec(2.0, -1.0)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L1497) ### `Vec.angle` ```cp fn angle(self) -> F64 ``` The polar angle `atan2(y, x)` in `(-pi, pi]`; a `-0.0` `y` counts as `0.0`, so the negative x axis gives `PI`, and the zero vector gives 0.0. - **cost**: O(1) - **traps**: never Examples: - `Vec(1.0, 0.0).angle == 0.0` - `Vec(-1.0, 0.0).angle == PI` - `Vec(0.0, 1.0).angle == PI / 2.0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L1507) ### `Vec.from_angle` ```cp fn from_angle(rad: F64) -> Vec ``` The unit vector `Vec(cos(rad), sin(rad))`. - **cost**: O(1) - **traps**: never Examples: - `Vec.from_angle(0.0) == Vec(1.0, 0.0)` - `close(Vec.from_angle(PI / 2.0).y, 1.0)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L1516) ### `Vec.unit` ```cp fn unit(self) -> Vec ``` The unit vector in the direction of `self`: each coordinate divided by `self.len`. - **cost**: O(1) - **traps**: when `self.len == 0.0` Examples: - `Vec(3.0, 4.0).unit == Vec(0.6, 0.8)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L1523) ### `Vec.rot` ```cp fn rot(self, by: Vec) -> Vec ``` `self` rotated by the direction `by`, as the complex product `self * by`: `Vec(x * by.x - y * by.y, x * by.y + y * by.x)`. A unit `by` rotates without scaling; get one from `Vec.from_angle`. - **cost**: O(1) - **traps**: never Examples: - `Vec(1.0, 2.0).rot(Vec(0.0, 1.0)) == Vec(-2.0, 1.0)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L1535) ### `Vec.dot` ```cp fn dot(self, o: Vec) -> F64 ``` The dot product `x * o.x + y * o.y`. - **cost**: O(1) - **traps**: never Examples: - `Vec(1.0, 2.0).dot(Vec(3.0, 4.0)) == 11.0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L1542) ### `Vec.cross` ```cp fn cross(self, o: Vec) -> F64 ``` The 2D cross product `x * o.y - y * o.x`: positive when `o` is counter-clockwise from `self`. - **cost**: O(1) - **traps**: never Examples: - `Vec(1.0, 2.0).cross(Vec(3.0, 4.0)) == -2.0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L1549) ### `Vec.dist2` ```cp fn dist2(self, o: Vec) -> F64 ``` The squared Euclidean distance from `self` to `o`. - **cost**: O(1) - **traps**: never Examples: - `Vec(0.0, 0.0).dist2(Vec(3.0, 4.0)) == 25.0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L1556) ### `Vec.dist` ```cp fn dist(self, o: Vec) -> F64 ``` The Euclidean distance from `self` to `o`. - **cost**: O(1) - **traps**: never Examples: - `Vec(0.0, 0.0).dist(Vec(3.0, 4.0)) == 5.0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L1563) ## `Vec` ```cp impl Add for Vec ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L1565) ### `Vec.add` ```cp fn add(a, b) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L1566) ## `Vec` ```cp impl Sub for Vec ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L1568) ### `Vec.sub` ```cp fn sub(a, b) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L1569) ## `Vec` ```cp impl Neg for Vec ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L1571) ### `Vec.neg` ```cp fn neg(a) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L1572) ## `Vec` ```cp impl Mul for Vec ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L1574) ### `Vec.mul` ```cp fn mul(a, k) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L1575) ## `Vec` ```cp impl Div for Vec ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L1577) ### `Vec.div` ```cp fn div(a, k) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L1578) ## `Circle` ```cp pub struct Circle(c: Vec, r: F64) ``` O(1) value type. A 2D circle with center `c` and non-negative radius `r`. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L1748) ### `Circle.through` ```cp fn through(a: Vec, b: Vec, c: Vec, eps: F64 = 1e-9) -> ?Circle ``` The circle through `a`, `b` and `c`: centre `circumcenter(a, b, c, eps)`, radius its distance to `a`; `None` when collinear. - **cost**: O(1) - **traps**: never Examples: - `Circle.through(Vec(0.0, 0.0), Vec(6.0, 0.0), Vec(0.0, 8.0)) == Some(Circle(Vec(3.0, 4.0), 5.0))` - `Circle.through(Vec(0.0, 0.0), Vec(1.0, 1.0), Vec(2.0, 2.0)) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L1756) ### `Circle.area` ```cp fn area(self) -> F64 ``` The disk area, computed as `PI * r * r`. - **cost**: O(1) - **traps**: never Examples: - `Circle(Vec(0.0, 0.0), 1.0).area == PI` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L1765) ### `Circle.circumference` ```cp fn circumference(self) -> F64 ``` The circumference, computed as `2.0 * PI * r`. - **cost**: O(1) - **traps**: never Examples: - `Circle(Vec(0.0, 0.0), 0.5).circumference == PI` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L1772) ### `Circle.locate` ```cp fn locate(self, p: Vec, eps: F64 = 1e-9) -> Location ``` Where `p` is relative to the disk, with `d = c.dist(p)`: `Boundary` when `|d - r| <= eps`, else `Inside` when `d < r`, else `Outside`. - **cost**: O(1) - **traps**: never Examples: - `Circle(Vec(0.0, 0.0), 5.0).locate(Vec(3.0, 4.0)) == Location.Boundary` - `Circle(Vec(0.0, 0.0), 5.0).locate(Vec(1.0, 1.0)) == Location.Inside` - `Circle(Vec(0.0, 0.0), 5.0).locate(Vec(6.0, 0.0)) == Location.Outside` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L1782) ## `HalfPlane` ```cp pub struct HalfPlane(p: Vec, dir: Vec) ``` O(1) value type. Directed line through `p` in direction `dir`, keeping the closed left half-plane `{ q | dir.cross(q - p) >= 0 }`. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L2011) ### `HalfPlane.through` ```cp fn through(a: Vec, b: Vec) -> HalfPlane ``` The closed half-plane left of the directed line `a -> b`: `HalfPlane(a, b - a)`. - **cost**: O(1) - **traps**: when `a == b` Examples: - `HalfPlane.through(Vec(0.0, 0.0), Vec(1.0, 0.0)) == HalfPlane(Vec(0.0, 0.0), Vec(1.0, 0.0))` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L2017) ### `HalfPlane.from_line` ```cp fn from_line(a: F64, b: F64, c: F64) -> HalfPlane ``` The half-plane `{ (x, y) | a*x + b*y + c >= 0 }`, as `HalfPlane(p, Vec(b, -a))` with `p` the line's point nearest the origin, `Vec(-a * c, -b * c) / (a*a + b*b)`. - **cost**: O(1) - **traps**: when `a == 0.0` and `b == 0.0` Examples: - `HalfPlane.from_line(0.0, 1.0, -2.0) == HalfPlane(Vec(0.0, 2.0), Vec(1.0, 0.0))` - `HalfPlane.from_line(1.0, 0.0, 0.0).side(Vec(3.0, 7.0)) == 3.0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L2028) ### `HalfPlane.side` ```cp fn side(self, q: Vec) -> F64 ``` The signed value `dir.cross(q - p)`: positive left of the line (inside), 0 on it, negative outside. It is `|dir|` times the signed distance. - **cost**: O(1) - **traps**: never Examples: - `HalfPlane.through(Vec(0.0, 0.0), Vec(1.0, 0.0)).side(Vec(3.0, 2.0)) == 2.0` - `HalfPlane.through(Vec(0.0, 0.0), Vec(1.0, 0.0)).side(Vec(3.0, -2.0)) == -2.0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L2040) ## `Rect` ```cp pub struct Rect(x: Range, y: Range) ``` O(1) value type. Half-open integer rectangle `x * y` (accepts cut ranges per decision 124). [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L2522) ### `Rect.area` ```cp fn area(self) -> Int ``` The number of unit cells, `x.len * y.len`; 0 when either range is empty. - **cost**: O(1) - **traps**: when the product overflows `Int` Examples: - `Rect(0..3, 0..2).area == 6` - `Rect(3..1, 0..2).area == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L2529) ### `Rect.is_empty` ```cp fn is_empty(self) -> Bool ``` Whether either axis range is empty. - **cost**: O(1) - **traps**: never Examples: - `Rect(0..0, 0..5).is_empty == true` - `Rect(0..1, 0..1).is_empty == false` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L2537) ### `Rect.contains` ```cp fn contains(self, p: Pt) -> Bool ``` Whether `p.x` is in `x` and `p.y` is in `y` (half-open, so the top and right edges are out). - **cost**: O(1) - **traps**: never Examples: - `Rect(0..3, 0..2).contains(Pt(2, 1)) == true` - `Rect(0..3, 0..2).contains(Pt(3, 1)) == false` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L2545) ### `Rect.intersect` ```cp fn intersect(self, o: Rect) -> ?Rect ``` The common part of two rectangles, or `None` when it is empty (including rectangles that only touch along an edge). - **cost**: O(1) - **traps**: never Examples: - `Rect(0..3, 0..3).intersect(Rect(1..5, 2..4)) == Some(Rect(1..3, 2..3))` - `Rect(0..1, 0..1).intersect(Rect(1..2, 0..1)) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L2554) ## `Pt3` ```cp pub struct Pt3(x: Int, y: Int, z: Int) ``` O(1) value type. A 3D point or vector with exact integer coordinates. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L2679) ### `Pt3.norm2` ```cp fn norm2(self) -> Int ``` The squared length `x*x + y*y + z*z`, in `Int`. - **cost**: O(1) - **traps**: when the result overflows `Int` Examples: - `Pt3(1, 2, 2).norm2 == 9` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L2685) ### `Pt3.norm2_128` ```cp fn norm2_128(self) -> I128 ``` The exact squared length, computed in `I128`. - **cost**: O(1) - **traps**: when the result overflows `I128` Examples: - `Pt3(1, 2, 2).norm2_128 == 9` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L2692) ### `Pt3.len` ```cp fn len(self) -> F64 ``` The Euclidean length as `F64`. - **cost**: O(1) - **traps**: never Examples: - `Pt3(1, 2, 2).len == 3.0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L2699) ### `Pt3.to_vec3` ```cp fn to_vec3(self) -> Vec3 ``` `self` as a floating-point `Vec3`: the explicit way across. - **cost**: O(1) - **traps**: never Examples: - `Pt3(1, 2, 2).to_vec3 == Vec3(1.0, 2.0, 2.0)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L2706) ### `Pt3.dot` ```cp fn dot(self, o: Pt3) -> Int ``` The dot product `x * o.x + y * o.y + z * o.z`, in `Int`. - **cost**: O(1) - **traps**: when the result or a product overflows `Int` Examples: - `Pt3(1, 2, 3).dot(Pt3(4, 5, 6)) == 32` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L2713) ### `Pt3.dot128` ```cp fn dot128(self, o: Pt3) -> I128 ``` The exact dot product, computed in `I128`. - **cost**: O(1) - **traps**: when the sum overflows `I128` Examples: - `Pt3(1, 2, 3).dot128(Pt3(4, 5, 6)) == 32` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L2720) ### `Pt3.cross` ```cp fn cross(self, o: Pt3) -> Pt3 ``` The cross product `Pt3(y*o.z - z*o.y, z*o.x - x*o.z, x*o.y - y*o.x)`, perpendicular to both by the right-hand rule. - **cost**: O(1) - **traps**: when a component overflows `Int` Examples: - `Pt3(1, 0, 0).cross(Pt3(0, 1, 0)) == Pt3(0, 0, 1)` - `Pt3(1, 2, 3).cross(Pt3(4, 5, 6)) == Pt3(-3, 6, -3)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L2729) ### `Pt3.dist2` ```cp fn dist2(self, o: Pt3) -> Int ``` The squared Euclidean distance from `self` to `o`, in `Int`. - **cost**: O(1) - **traps**: when the result overflows `Int` Examples: - `Pt3(0, 0, 0).dist2(Pt3(1, 2, 2)) == 9` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L2736) ### `Pt3.dist` ```cp fn dist(self, o: Pt3) -> F64 ``` The Euclidean distance from `self` to `o`, as `F64`. - **cost**: O(1) - **traps**: never Examples: - `Pt3(0, 0, 0).dist(Pt3(1, 2, 2)) == 3.0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L2743) ### `Pt3.manhattan` ```cp fn manhattan(self, o: Pt3) -> Int ``` The Manhattan (L1) distance `|x - o.x| + |y - o.y| + |z - o.z|`. - **cost**: O(1) - **traps**: when the result overflows `Int` Examples: - `Pt3(1, 1, 1).manhattan(Pt3(2, -1, 4)) == 6` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L2750) ### `Pt3.chebyshev` ```cp fn chebyshev(self, o: Pt3) -> Int ``` The Chebyshev (L-infinity) distance `max(|x - o.x|, |y - o.y|, |z - o.z|)`. - **cost**: O(1) - **traps**: when the result overflows `Int` Examples: - `Pt3(1, 1, 1).chebyshev(Pt3(2, -1, 4)) == 3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L2757) ## `Pt3` ```cp impl Add for Pt3 ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L2759) ### `Pt3.add` ```cp fn add(a, b) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L2760) ## `Pt3` ```cp impl Sub for Pt3 ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L2762) ### `Pt3.sub` ```cp fn sub(a, b) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L2763) ## `Pt3` ```cp impl Neg for Pt3 ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L2765) ### `Pt3.neg` ```cp fn neg(a) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L2766) ## `Pt3` ```cp impl Mul for Pt3 ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L2768) ### `Pt3.mul` ```cp fn mul(a, k) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L2769) ## `Pt3` ```cp impl Show for Pt3 ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L2771) ### `Pt3.show` ```cp fn show(a) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L2772) ## `Vec3` ```cp pub struct Vec3(x: F64, y: F64, z: F64) ``` O(1) value type. A 3D floating-point point or vector. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L2971) ### `Vec3.norm2` ```cp fn norm2(self) -> F64 ``` The squared length `x*x + y*y + z*z`. - **cost**: O(1) - **traps**: never Examples: - `Vec3(1.0, 2.0, 2.0).norm2 == 9.0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L2977) ### `Vec3.len` ```cp fn len(self) -> F64 ``` The Euclidean length. - **cost**: O(1) - **traps**: never Examples: - `Vec3(1.0, 2.0, 2.0).len == 3.0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L2984) ### `Vec3.unit` ```cp fn unit(self) -> Vec3 ``` The unit vector in the direction of `self`: each coordinate divided by `self.len`. - **cost**: O(1) - **traps**: when `self.len == 0.0` Examples: - `Vec3(0.0, 0.0, 2.0).unit == Vec3(0.0, 0.0, 1.0)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L2991) ### `Vec3.dot` ```cp fn dot(self, o: Vec3) -> F64 ``` The dot product `x * o.x + y * o.y + z * o.z`. - **cost**: O(1) - **traps**: never Examples: - `Vec3(1.0, 2.0, 3.0).dot(Vec3(4.0, 5.0, 6.0)) == 32.0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L3001) ### `Vec3.cross` ```cp fn cross(self, o: Vec3) -> Vec3 ``` The cross product, by the right-hand rule, as for `Pt3.cross`. - **cost**: O(1) - **traps**: never Examples: - `Vec3(1.0, 0.0, 0.0).cross(Vec3(0.0, 1.0, 0.0)) == Vec3(0.0, 0.0, 1.0)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L3008) ### `Vec3.dist2` ```cp fn dist2(self, o: Vec3) -> F64 ``` The squared Euclidean distance from `self` to `o`. - **cost**: O(1) - **traps**: never Examples: - `Vec3(0.0, 0.0, 0.0).dist2(Vec3(1.0, 2.0, 2.0)) == 9.0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L3015) ### `Vec3.dist` ```cp fn dist(self, o: Vec3) -> F64 ``` The Euclidean distance from `self` to `o`. - **cost**: O(1) - **traps**: never Examples: - `Vec3(0.0, 0.0, 0.0).dist(Vec3(1.0, 2.0, 2.0)) == 3.0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L3022) ### `Vec3.rot` ```cp fn rot(self, axis: Vec3, rad: F64) -> Vec3 ``` `self` rotated by `rad` radians counter-clockwise about the unit vector `axis` (seen with `axis` pointing at the viewer), by Rodrigues' formula `v cos t + axis.cross(v) sin t + axis * axis.dot(v) * (1 - cos t)`. `axis` must be a unit vector; that is not checked. - **cost**: O(1) - **traps**: never Examples: - `Vec3(1.0, 2.0, 3.0).rot(Vec3(0.0, 0.0, 1.0), 0.0) == Vec3(1.0, 2.0, 3.0)` - `let v = Vec3(1.0, 0.0, 0.0).rot(Vec3(0.0, 0.0, 1.0), PI / 2.0); close(v.x, 0.0) and close(v.y, 1.0) and close(v.z, 0.0)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L3034) ## `Vec3` ```cp impl Add for Vec3 ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L3036) ### `Vec3.add` ```cp fn add(a, b) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L3037) ## `Vec3` ```cp impl Sub for Vec3 ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L3039) ### `Vec3.sub` ```cp fn sub(a, b) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L3040) ## `Vec3` ```cp impl Neg for Vec3 ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L3042) ### `Vec3.neg` ```cp fn neg(a) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L3043) ## `Vec3` ```cp impl Mul for Vec3 ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L3045) ### `Vec3.mul` ```cp fn mul(a, k) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L3046) ## `Vec3` ```cp impl Div for Vec3 ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L3048) ### `Vec3.div` ```cp fn div(a, k) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L3049) ## `Plane3` ```cp pub struct Plane3(n: Vec3, d: F64) ``` O(1) value type. A 3D plane `{ p | n.dot(p) == d }` with unit normal `n`. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L3052) ### `Plane3.through` ```cp fn through(a: Vec3, b: Vec3, c: Vec3, eps: F64 = 1e-9) -> ?Plane3 ``` The plane through `a`, `b` and `c`: `n = (b - a).cross(c - a).unit`, `d = n.dot(a)`; `None` when `(b - a).cross(c - a).len <= eps` (collinear). The normal follows the right-hand rule, so `a -> b -> c` runs counter-clockwise seen from the side `n` points to. - **cost**: O(1) - **traps**: never Examples: - `Plane3.through(Vec3(0.0, 0.0, 1.0), Vec3(1.0, 0.0, 1.0), Vec3(0.0, 1.0, 1.0)) == Some(Plane3(Vec3(0.0, 0.0, 1.0), 1.0))` - `Plane3.through(Vec3(0.0, 0.0, 0.0), Vec3(1.0, 1.0, 1.0), Vec3(2.0, 2.0, 2.0)) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L3063) ### `Plane3.dist` ```cp fn dist(self, p: Vec3) -> F64 ``` The signed distance `n.dot(p) - d`: positive on the side `n` points to. - **cost**: O(1) - **traps**: never Examples: - `Plane3(Vec3(0.0, 0.0, 1.0), 1.0).dist(Vec3(5.0, 5.0, 3.0)) == 2.0` - `Plane3(Vec3(0.0, 0.0, 1.0), 1.0).dist(Vec3(5.0, 5.0, 0.0)) == -1.0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L3075) ### `Plane3.project` ```cp fn project(self, p: Vec3) -> Vec3 ``` The orthogonal projection of `p` onto the plane: `p - n * self.dist(p)`. - **cost**: O(1) - **traps**: never Examples: - `Plane3(Vec3(0.0, 0.0, 1.0), 1.0).project(Vec3(5.0, 5.0, 3.0)) == Vec3(5.0, 5.0, 1.0)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/geometry.cp#L3082) --- # graph URL: /docs/ref/std/graph Generated from [spec/std/graph.cp](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp) by `cpl doc --format json`. ## `Next` ```cp pub trait Next ``` O(deg u) per walk of `out(u)`. What every graph algorithm walks: the arcs out of `u`. Implemented by `Graph`, by any `[V]S` with `S: Seq` of arcs, and by any fn `V -> Seq`. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L26) ### `Next.Arc` ```cp type Arc: Target ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L27) ### `Next.out` ```cp fn out(self, u: V) -> yields Self.Arc ``` The arcs out of `u`, lazily. Every graph algorithm reads the graph only through this. - **cost**: O(1) per arc yielded - **order**: the implementation's arc order (input order for `Graph`, list order for `[V]List`) - **traps**: never Examples: - `domain V = 0..3; let g: [V]List = [[2, 1], [], []]; g.out(0).collect() == [2, 1]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L34) ## `Target` ```cp pub trait Target ``` O(1). Where an arc leads. A plain vertex is its own target, and a record with a `to: V` field is one (a field is a `@get`). [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L38) ### `Target.to` ```cp fn to(self) -> V ``` The vertex an arc leads to. A plain vertex is its own target; a record's `to` field is its target. - **cost**: O(1) - **traps**: never Examples: - `domain V = 0..3; V(2).to == 2` - `domain V = 0..3; let a: (to: V, w: Int) = (to: 1, w: 7); a.to == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L46) ## `Weighted` ```cp pub trait Weighted ``` O(1). The weight of an arc: a record with a `w` field, or `.weighted(f)`. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L49) ### `Weighted.w` ```cp fn w(self) -> W ``` The weight of an arc: its `w` field, or `f(a)` through `g.weighted(f)`. - **cost**: O(1) plus the cost of `f` under `weighted` - **traps**: never Examples: - `domain V = 0..3; let a: (to: V, w: Int) = (to: 1, w: 7); a.w == 7` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L55) ## `Edged` ```cp pub trait Edged ``` O(1). The edge an arc belongs to; both arcs of an undirected edge share it. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L58) ### `Edged.e` ```cp fn e(self) -> E ``` The edge an arc belongs to. Both arcs of an undirected edge carry the same `e`. - **cost**: O(1) - **traps**: never Examples: - `domain V = 0..2; domain E = 0..1; let es: [E](u: V, v: V) = [(u: 0, v: 1)]; let g = Graph.undirected(es); g.out(0).collect()[0].e == g.out(1).collect()[0].e` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L64) ## `WeightedNext` ```cp pub trait WeightedNext = Next where Self.Arc ``` A graph whose arcs carry weights: shortest paths, MST over arcs, DAG folds. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L67) ## `EdgedNext` ```cp pub trait EdgedNext = Next where Self.Arc ``` A graph whose arcs carry edge ids: bridges, two-edge components, edge blocks. These skip the arc back along the same edge, not to the same vertex, so parallel edges are right. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L72) ## `EdgeArc` ```cp pub type EdgeArc = (to: V, e: E, ..R without (u, v)) ``` The arc a build stores by default: the target, the edge id, and every field of the edge record except `u` and `v`. Every carried field must be plain; a heap field is a compile error that points at `keep:`. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L77) ## `Reweighted` ```cp pub struct Reweighted ``` O(1) per arc read: `g.weighted(f)`, the arcs of `g` with `.w` read as `f(a)` (or `f(u, a)`), `.to` and `.e` passed through. Nothing is stored. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L81) ## `Tree` ```cp pub type Tree = [0..V.len - 1](u: V, v: V) ``` O(n) to read. The `V.len - 1` edges of a tree on `V`, one `u v` pair per line, as an input gives them. `cpl stress` makes and shrinks it as a tree. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L88) ## `SimpleGraph` ```cp pub type SimpleGraph = [E](u: V, v: V) ``` O(m) to read. One edge on `V` for each value of `E`, `u v` per line, with no loop and no pair twice. `cpl stress` makes and shrinks it so. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L93) ## `ConnectedGraph` ```cp pub type ConnectedGraph = [E](u: V, v: V) ``` O(n + m) to read (connectivity is validated). A `SimpleGraph` in which every vertex reaches every other. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L97) ## `Dag` ```cp pub type Dag = [E](u: V, v: V) ``` O(m) to read. One arc `u -> v` on `V` for each value of `E`, with no arc twice and no directed cycle. `cpl stress` makes and shrinks it so. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L102) ## `Digraph` ```cp pub type Digraph = [E](u: V, v: V) ``` O(n + m) to read (acyclicity is validated). One arc `u -> v` on `V` for each value of `E`, with no loop and no arc twice; `u v` and `v u` are two arcs. `cpl stress` makes and shrinks it so. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L107) ## `Graph` ```cp pub struct Graph> ``` O(n + m) memory and build. A fixed graph in compressed sparse row form: n + 1 offsets and one arcs list, the arcs of each vertex contiguous and in input order. Immutable; a graph that grows is a `[V]List` of arcs, which is already a `Next`. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L113) ### `Graph.directed` ```cp fn directed>( edges: [E]R, keep: EdgeArc -> B = a => a, ) -> Graph ``` A graph with one arc `u -> v` per edge of `edges`, in compressed sparse rows. The arcs out of each vertex keep the order of their edges in `edges` (a stable counting sort), so DFS orders and first-found answers are deterministic. Each arc is `EdgeArc`, the edge record with `u`, `v` replaced by `to`, `e`, unless `keep` maps it to something else; `keep` runs once per arc at build and what it returns is stored. - **cost**: O(n + m) time and memory, plus `m` calls of `keep` - **empty**: no edges gives every vertex no arcs; an empty `V` gives the empty graph - **traps**: never Examples: - `domain V = 0..3; domain E = 0..2; let es: [E](u: V, v: V) = [(u: 0, v: 2), (u: 0, v: 1)]; Graph.directed(es).out(0).collect() == [(to: 2, e: 0), (to: 1, e: 1)]` - `domain V = 0..3; domain E = 0..2; let es: [E](u: V, v: V) = [(u: 0, v: 2), (u: 0, v: 1)]; Graph.directed(es, keep: a => (to: a.to)).out(0).collect() == [(to: 2), (to: 1)]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L130) ### `Graph.undirected` ```cp fn undirected>( edges: [E]R, keep: EdgeArc -> B = a => a, ) -> Graph ``` A graph with two arcs per edge of `edges`, `u -> v` and `v -> u`, both carrying the same `e`. A loop `u -> u` gives two arcs at `u`, so it counts twice in `deg`. The arcs out of each vertex come in the order of their edges in `edges`; a loop's two arcs are adjacent. `keep` runs once per stored arc, so `2m` times. - **cost**: O(n + m) time and memory, plus `2m` calls of `keep` - **empty**: no edges gives every vertex no arcs - **traps**: never Examples: - `domain V = 0..3; domain E = 0..2; let es: [E](u: V, v: V) = [(u: 0, v: 1), (u: 1, v: 2)]; Graph.undirected(es).out(1).collect() == [(to: 0, e: 0), (to: 2, e: 1)]` - `domain V = 0..1; domain E = 0..1; let es: [E](u: V, v: V) = [(u: 0, v: 0)]; Graph.undirected(es).deg(0) == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L170) ### `Graph.of` ```cp fn of(arcs: Seq<(from: V, arc: A)>) -> Graph ``` A graph from `(from, arc)` pairs: `arc` is stored as one of `from`'s arcs. The base form the other builders reduce to. - **cost**: O(n + m) - **empty**: no pairs gives every vertex no arcs - **order**: each vertex's arcs in the order the pairs come - **traps**: never Examples: - `domain V = 0..2; let g = Graph.of([(from: V(1), arc: V(0)), (from: V(0), arc: V(1)), (from: V(1), arc: V(1))]); g.next(1).collect() == [0, 1]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L212) ### `Graph.at` ```cp fn at(self, u: V) -> lends Slice ``` `g[u]`: the arcs out of `u` as an `Indexed` view, without copying. The view is a slice of the graph's arc list, so like every slice it keeps its source's keys: `start[u]..start[u + 1]`. Iterate it, or use `.first`, `.len` and `.to_list()`. - **cost**: O(1) - **order**: the arcs in input order - **traps**: never Examples: - `domain V = 0..3; domain E = 0..2; let es: [E](u: V, v: V) = [(u: 0, v: 2), (u: 0, v: 1)]; let g = Graph.directed(es); g[0].len == 2 and g[1].len == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L246) ### `Graph.out` ```cp fn out(self, u: V) -> yields A ``` The arcs out of `u`, lazily: the `Next` implementation. - **cost**: O(1) to make, O(1) per arc - **order**: input order - **traps**: never Examples: - `domain V = 0..3; domain E = 0..2; let es: [E](u: V, v: V) = [(u: 0, v: 2), (u: 0, v: 1)]; Graph.directed(es).out(0).collect() == [(to: 2, e: 0), (to: 1, e: 1)]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L254) ### `Graph.matrix` ```cp fn matrix(self) -> [V, V]?W where A: Weighted ``` The weight matrix: `d[u, v]` is the least `.w` over the arcs `u -> v`, `None` without one. The diagonal holds the least loop weight, or `None`; `floyd_warshall` starts it at zero itself. - **cost**: O(n^2 + m) time, O(n^2) memory - **ties**: parallel arcs keep the least weight - **traps**: never Examples: - `domain V = 0..2; domain E = 0..3; let es: [E](u: V, v: V, w: Int) = [(u: 0, v: 1, w: 5), (u: 0, v: 1, w: 3), (u: 1, v: 0, w: 4)]; let d = Graph.directed(es).matrix(); d[0, 1] == Some(3) and d[1, 0] == Some(4) and d[0, 0] == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L267) ### `Graph.deg` ```cp fn deg(self, u: V) -> Int ``` The number of arcs out of `u`. An undirected loop counts twice. - **cost**: O(1) - **traps**: never Examples: - `domain V = 0..3; domain E = 0..2; let es: [E](u: V, v: V) = [(u: 0, v: 1), (u: 1, v: 2)]; Graph.undirected(es).deg(1) == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L285) ### `Graph.next` ```cp fn next(self, u: V) -> yields V ``` Where `u`'s arcs lead: `out(u)` mapped to `.to`, repeats kept. - **cost**: O(1) per vertex yielded - **order**: input order - **traps**: never Examples: - `domain V = 0..3; domain E = 0..2; let es: [E](u: V, v: V) = [(u: 0, v: 2), (u: 0, v: 1)]; Graph.directed(es).next(0).collect() == [2, 1]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L293) ### `Graph.only` ```cp fn only(self, keep: V -> Bool = v => true, from: V -> Bool = v => true) -> Only ``` The induced view on the vertices `keep` accepts: arcs from or to a rejected vertex are skipped. `from` also skips the arcs leaving a vertex it rejects, so that vertex can be reached but not left. Rejected vertices stay in `V` with no arcs. See the free `only`. - **cost**: O(1) to make; `keep` and `from` run per arc walked - **traps**: never Examples: - `domain V = 0..4; domain E = 0..4; let es: [E](u: V, v: V) = [(u: 0, v: 1), (u: 0, v: 2), (u: 1, v: 3), (u: 2, v: 3)]; Graph.directed(es).only(keep: v => v != 1).deg(0) == 1` - `domain V = 0..4; domain E = 0..4; let es: [E](u: V, v: V) = [(u: 0, v: 1), (u: 0, v: 2), (u: 1, v: 3), (u: 2, v: 3)]; let h = Graph.directed(es).only(from: v => v != 1); h.deg(0) == 2 and h.deg(1) == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L306) ### `Graph.weighted` ```cp fn weighted(self, f: A -> W) -> lends Reweighted, A -> W> ``` The same graph with each arc's `.w` read as `f(a)`; `.to` and `.e` pass through, so it is a `WeightedNext` and stays `Edged`. On a weighted graph it reweights. Nothing is stored. - **cost**: O(1) to make; `f` runs on every arc read - **traps**: never Examples: - `domain V = 0..3; domain E = 0..2; let es: [E](u: V, v: V) = [(u: 0, v: 1), (u: 1, v: 2)]; dijkstra(Graph.directed(es).weighted(a => 5), from: [(V(0), 0)])[2] == Some(10)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L316) ### `Graph.spanning_tree` ```cp fn spanning_tree(self) -> Rooted ``` A BFS spanning tree rooted at `V.first`, as a `Rooted`. Each vertex's parent is the vertex whose arc first reached it, scanning vertices in BFS order and arcs in input order. A forest is `spanning_forest`. - **cost**: O(n + m) - **traps**: when the graph is not connected from `V.first`, or `V` is empty Examples: - `domain V = 0..3; domain E = 0..2; let es: [E](u: V, v: V) = [(u: 0, v: 1), (u: 1, v: 2)]; let t = Graph.undirected(es).spanning_tree(); t.parent(2) == Some(1) and t.parent(0) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L325) ### `Graph.has` ```cp fn has(self, u: V, v: V) -> Bool ``` True when some arc `u -> v` exists. A scan of `u`'s arcs, not a lookup. - **cost**: O(deg u) - **traps**: never Examples: - `domain V = 0..3; domain E = 0..2; let es: [E](u: V, v: V) = [(u: 0, v: 2), (u: 0, v: 1)]; let g = Graph.directed(es); g.has(0, 2) and not g.has(2, 0)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L332) ### `Graph.lists` ```cp fn lists(self) -> [V]List ``` The targets of every vertex as plain lists, `lists()[u] == next(u).collect()`: the shape `std.flow` matchings take. - **cost**: O(n + m) - **order**: keyed by `V`; each list in input order, repeats kept - **traps**: never Examples: - `domain V = 0..3; domain E = 0..2; let es: [E](u: V, v: V) = [(u: 0, v: 2), (u: 0, v: 1)]; Graph.directed(es).lists()[0] == [2, 1]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L344) ### `Graph.hops` ```cp fn hops(self) -> [V, V]Int ``` The fewest arcs between every ordered pair, by a BFS from each vertex; `0` on the diagonal. A graph with unreachable pairs wants `bfs`. - **cost**: O(n (n + m)) time, O(n^2) memory - **order**: keyed by `(from, to)` - **traps**: when some vertex cannot reach another Examples: - `domain V = 0..3; domain E = 0..2; let es: [E](u: V, v: V) = [(u: 0, v: 1), (u: 1, v: 2)]; let h = Graph.undirected(es).hops(); h[0, 2] == 2 and h[1, 1] == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L354) ### `Graph.edges` ```cp fn edges(self) -> yields Edge where A: Edged ``` Every edge once, as `Edge(e, u, v)` with its ends as given to the build. Needs arcs that keep `e`; the graph keeps one source arc per edge. - **cost**: O(1) to make, O(1) per edge - **order**: increasing `e` - **traps**: never Examples: - `domain V = 0..3; domain E = 0..2; let es: [E](u: V, v: V) = [(u: 1, v: 0), (u: 0, v: 2)]; Graph.undirected(es).edges().collect() == [Edge(0, 1, 0), Edge(1, 0, 2)]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L380) ### `Graph.dfs_tree` ```cp fn dfs_tree(self, root: V) -> (tree: Rooted, tree_edge: [E]Bool) where A: Edged ``` The DFS tree from `root` of the component holding it, as a `Rooted` tree and a mask of the edges it uses. The search takes arcs in input order and descends at once (recursive order, run without recursion). On an undirected graph every edge with `tree_edge[e] == false` then joins a vertex to one of its ancestors in `tree`, which is what bridges, cut vertices and back-edge DPs need. Vertices outside the component are not in `tree`. - **cost**: O(n + m) - **order**: children in the order the search reached them - **traps**: never Examples: - `domain V = 0..3; domain E = 0..3; let es: [E](u: V, v: V) = [(u: 0, v: 1), (u: 1, v: 2), (u: 2, v: 0)]; let (tree, tree_edge) = Graph.undirected(es).dfs_tree(0); tree.parent(2) == Some(1) and tree.depth(2) == 2 and tree_edge == [true, true, false]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L406) ### `Graph.peel` ```cp fn peel( self, ready: ?(V -> Bool) = None, on_remove: ?((V, A) -> ()) = None, ) -> List ``` `peel(g, ready:, on_remove:)` as a method; see the free `peel`. - **cost**: O(n + m) plus the calls of `ready` and `on_remove` - **order**: removal order - **traps**: never Examples: - `domain V = 0..4; domain E = 0..4; let es: [E](u: V, v: V) = [(u: 0, v: 1), (u: 0, v: 2), (u: 1, v: 3), (u: 2, v: 3)]; Graph.directed(es).peel() == [0, 1, 2, 3]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L415) ### `Graph.transpose` ```cp fn transpose(self) -> Graph where A: (to: V, ..) ``` Every arc `u -> a.to` reversed to `a.to -> u`, its other fields kept (`(..a, to: u)`). - **cost**: O(n + m) - **order**: each vertex's new arcs by original source in vertex order, then input order - **traps**: never Examples: - `domain V = 0..4; domain E = 0..4; let es: [E](u: V, v: V) = [(u: 0, v: 1), (u: 0, v: 2), (u: 1, v: 3), (u: 2, v: 3)]; Graph.directed(es).transpose().out(3).collect() == [(to: 1, e: 2), (to: 2, e: 3)]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L460) ## `Paths` ```cp pub struct Paths ``` O(n) memory. What a search found: `p[v]` is the distance to `v` (`None` if unreachable), `back[v]` is `(from, via)`, the vertex before `v` on one shortest path and the arc or move that reached it (`None` at a source), and `order` the reached vertices in settling order, so every vertex comes after its `from` and distances never decrease. A search given `until: t` stops once `t` is settled: distances in `order` are exact, and any other vertex holds `None` or an upper bound. Cost: the witnesses take one slot per vertex and one write per improving relaxation, paid even when only `p[v]` is read. Storage is spelled like `@memo(array)` / `@memo(map)`: by default `dist` and `back` are dense tables over `V`, which must be a bounded type (a domain, range, enum or a tuple of them); `hashed: true` on the search makes them hash maps over the states reached, for state spaces like `Int` values or unbounded tuples. An unbounded `V` without it is a compile error that names `hashed: true`. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L955) ### `Paths.get` ```cp fn get(self, v: V) -> ?W ``` `p[v]`: the distance to `v`, or `None` if no source reaches it (or the search stopped at `until` first). - **cost**: O(1) dense, O(1) expected `hashed` - **traps**: never Examples: - `domain V = 0..4; let g: [V]List = [[1, 2], [3], [3], []]; let p = bfs(g, from: [V(0)]); p[3] == Some(2) and p[0] == Some(0)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L966) ### `Paths.iter` ```cp fn iter(self) -> yields (v: V, d: W) ``` The reached vertices with their distances, in settling order: `for (v, d) in bfs(g, from: [s])`. - **cost**: O(1) to make, O(1) per item - **order**: settling order (the `order` list), so distances never decrease for `bfs`, `bfs01`, `dial`, `dijkstra` and `fixed_cost_paths`; for `bellman_ford` each vertex comes after its parent - **traps**: never Examples: - `domain V = 0..3; let g: [V]List = [[1], [2], []]; bfs(g, from: [V(0)]).iter().collect() == [(v: 0, d: 0), (v: 1, d: 1), (v: 2, d: 2)]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L975) ### `Paths.tight` ```cp fn tight<>(self, g: Next) -> [V]List ``` The arcs on some shortest path: for each reached `u`, the arcs `a` of `g.out(u)` with `p[a.to] == p[u] + w(a)`, where `w(a)` is `a.w` for `Weighted` arcs and `1` otherwise. Walking `order` over this DAG counts or lists shortest paths. - **cost**: O(n + m) - **order**: keyed by `V`; each list in arc order; unreached vertices get `[]` - **traps**: never Examples: - `domain V = 0..4; let g: [V]List = [[1, 2], [3], [3], []]; let t = bfs(g, from: [V(0)]).tight(g); t[0] == [1, 2] and t[2] == [3] and t[3] == []` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L987) ### `Paths.reached` ```cp fn reached(self, v: V) -> Bool ``` Does some source reach `v`? `p[v] != None`. - **cost**: O(1) - **traps**: never Examples: - `domain V = 0..3; let g: [V]List = [[1], [], []]; let p = bfs(g, from: [V(0)]); p.reached(1) and not p.reached(2)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L1002) ### `Paths.path` ```cp fn path(self, t: V) -> ?List ``` The vertices of one shortest path from a source to `t`, both included, or `None` if `t` is unreachable; `[t]` when `t` is a source. Built from the back pointers, each set by the arc that first gave its vertex the final distance. - **cost**: O(path length) - **ties**: the path through the arc that first reached each vertex at its final distance - **order**: from the source to `t` - **traps**: never Examples: - `domain V = 0..4; let g: [V]List = [[1, 2], [3], [3], []]; bfs(g, from: [V(0)]).path(3) == Some([0, 1, 3])` - `domain V = 0..2; let g: [V]List = [[], []]; let p = bfs(g, from: [V(0)]); p.path(0) == Some([0]) and p.path(1) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L1014) ### `Paths.arcs` ```cp fn arcs(self, t: V) -> ?List ``` The arcs of `path(t)`, in walking order: `[]` when `t` is a source, `None` if it is unreachable. - **cost**: O(path length) - **ties**: as `path` - **order**: from the source to `t` - **traps**: never Examples: - `domain V = 0..4; let g: [V]List = [[1, 2], [3], [3], []]; bfs(g, from: [V(0)]).arcs(3) == Some([1, 3])` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L1032) ## `Walk` ```cp pub struct Walk ``` O(m) memory. A walk: where it starts, then each arc taken (`to` is where the arc leads, `e` the edge it uses), the same arcs a `Graph` yields. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L1429) ### `Walk.vertices` ```cp fn vertices(self) -> yields V ``` The vertices visited, `start` first, then each arc's `to`: `arcs.len + 1` of them. - **cost**: O(1) to make, O(1) per vertex - **order**: walking order - **traps**: never Examples: - `domain V = 0..3; domain E = 0..2; let es: [E](u: V, v: V) = [(u: 0, v: 1), (u: 1, v: 2)]; euler_walk(es, directed: false)!.vertices.collect() == [0, 1, 2]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L1439) ## `Lit` ```cp pub struct Lit(x: X, value: Bool) ``` O(1). A variable or its negation: `Lit(x, true)` is "x holds". [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L1497) ### `Lit.flip` ```cp fn flip(self) -> Lit ``` The opposite literal: `Lit(x, v).flip == Lit(x, not v)`. - **cost**: O(1) - **traps**: never Examples: - `domain X = 0..2; Lit(X(1), true).flip == Lit(X(1), false)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L1503) ## `TwoSat` ```cp pub struct TwoSat ``` A conjunction of two-literal clauses over the variables `X`. Every clause is O(1) to add; `solve` is O(|X| + clauses). [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L1507) ### `TwoSat.imp` ```cp imp: List> ``` Implications between literal nodes: node `2 * i` is "variable i is false", `2 * i + 1` "is true"; variables past `X.K` are helpers of `at_most_one`. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L1510) ### `TwoSat.new` ```cp fn new() -> TwoSat ``` An instance with no clauses over the variables of `X`; every assignment satisfies it. - **cost**: O(|X|) - **traps**: never Examples: - `domain X = 0..2; TwoSat().solve() != None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L1517) ### `TwoSat.add_or` ```cp fn add_or(mut self, a: Lit, b: Lit) ``` Adds the clause "at least one of `a`, `b` holds". - **cost**: O(1) amortized - **traps**: never Examples: - `domain X = 0..2; var s = TwoSat(); s.add_or(Lit(X(0), true), Lit(X(1), true)); s.must(Lit(X(0), false)); s.solve() == Some([false, true])` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L1525) ### `TwoSat.must` ```cp fn must(mut self, a: Lit) ``` Adds the clause "`a` holds" (`add_or(a, a)`). - **cost**: O(1) amortized - **traps**: never Examples: - `domain X = 0..1; var s = TwoSat(); s.must(Lit(X(0), true)); s.must(Lit(X(0), false)); s.solve() == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L1533) ### `TwoSat.implies` ```cp fn implies(mut self, a: Lit, b: Lit) ``` Adds "if `a` holds then `b` holds" (`add_or(a.flip, b)`). - **cost**: O(1) amortized - **traps**: never Examples: - `domain X = 0..2; var s = TwoSat(); s.implies(Lit(X(0), true), Lit(X(1), true)); s.must(Lit(X(0), true)); s.solve() == Some([true, true])` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L1541) ### `TwoSat.at_most_one` ```cp fn at_most_one(mut self, lits: List>) ``` Adds "at most one of `lits` holds". One helper variable per literal ("some literal so far holds") keeps it at O(k) clauses instead of O(k^2); helpers never appear in `solve`'s result. - **cost**: O(k) amortized - **empty**: `[]` adds nothing - **traps**: never Examples: - `domain X = 0..2; var s = TwoSat(); s.at_most_one([Lit(X(0), true), Lit(X(1), true)]); s.must(Lit(X(0), true)); s.solve() == Some([true, false])` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L1552) ### `TwoSat.add_xor` ```cp fn add_xor(mut self, a: Lit, b: Lit) ``` Adds "exactly one of `a`, `b` holds" (two clauses). - **cost**: O(1) amortized - **traps**: never Examples: - `domain X = 0..2; var s = TwoSat(); s.add_xor(Lit(X(0), true), Lit(X(1), true)); s.must(Lit(X(0), true)); s.solve() == Some([true, false])` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L1570) ### `TwoSat.add_eq` ```cp fn add_eq(mut self, a: Lit, b: Lit) ``` Adds "`a` and `b` hold together or not at all" (two clauses). - **cost**: O(1) amortized - **traps**: never Examples: - `domain X = 0..2; var s = TwoSat(); s.add_eq(Lit(X(0), true), Lit(X(1), true)); s.must(Lit(X(1), false)); s.solve() == Some([false, false])` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L1579) ### `TwoSat.solve` ```cp fn solve(self) -> ?[X]Bool ``` An assignment satisfying every clause, or `None` if there is None. Runs `scc` on the implication graph (node `2i` is "variable `i` is false", `2i + 1` "is true"; clause `a or b` adds `not a -> b` then `not b -> a`, in the order added). A variable is true exactly when its true node's component comes after its false node's in `scc`'s topological order, so the assignment is a function of the clauses and their order. - **cost**: O(|X| + clauses) - **order**: keyed by `X` - **traps**: never Examples: - `domain X = 0..1; var s = TwoSat(); s.implies(Lit(X(0), true), Lit(X(0), false)); s.solve() == Some([false])` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L1594) ### `TwoSat.clause` ```cp fn clause(mut self, a: Int, b: Int) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L1603) ## `Visit` ```cp pub enum Visit: Enter(v: V, via: ?A), Exit(v: V, via: ?A), Again(from: V, via ``` O(1): one event of `dfs`, the same shape as `Rooted.tour` yields: `via` is the arc that discovered `v` (`None` for a source); `Again(from, via)` is an arc into a discovered vertex. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L1783) ### `Visit.Enter` ```cp Enter(v: V, via: ?A) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L1783) ### `Visit.Exit` ```cp Exit(v: V, via: ?A) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L1783) ### `Visit.Again` ```cp Again(from: V, via: A) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L1783) ## `Complement` ```cp pub struct Complement(missing: G) ``` The complement of `missing` over a domain `V`: an arc `u -> v` for every `v != u` that `missing.out(u)` does not reach. Its own `out(u)` is O(|V|), but `bfs`, `dfs`, `reachable` and `components` over a `Complement` run in O(|V| + m) by keeping the set of unvisited vertices and scanning only it, so "BFS in the complement graph" and its components are the ordinary searches: `components(complement(g))`. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L2250) ### `Complement.out` ```cp fn out(self, u: V) -> yields V ``` Every `v != u` that `missing.out(u)` does not reach. - **cost**: O(|V| + deg u) - **order**: ascending - **traps**: never Examples: - `domain V = 0..4; let g: [V]List = [[1], [0], [], []]; complement(g).out(0).collect() == [2, 3]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L2257) ## `Functional` ```cp pub struct Functional ``` O(n) build: the functional graph `v -> next[v]` (every vertex one out-arc). [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L2623) ## `Functional` ```cp impl Functional ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L2633) ### `Functional.new` ```cp fn new(next: [V]V) -> Functional ``` The functional graph `v -> next[v]` (every vertex has one out-arc), with its cycles, tails and binary-lifting tables built. - **cost**: O(n log n) - **empty**: an empty `V` gives an empty graph - **traps**: never Examples: - `domain V = 0..5; let nx: [V]V = [1, 2, 0, 0, 3]; Functional(nx).cycle_len(4) == 3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L2641) ### `Functional.on_cycle` ```cp fn on_cycle(self, v: V) -> Bool ``` Does `v` lie on a cycle? - **cost**: O(1) - **traps**: never Examples: - `domain V = 0..5; let nx: [V]V = [1, 2, 0, 0, 3]; let f = Functional(nx); f.on_cycle(1) and not f.on_cycle(3)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L2690) ### `Functional.root_of` ```cp fn root_of(self, v: V) -> V ``` The first cycle vertex reached from `v` (`v` itself on a cycle): the root of the in-tree hanging off the cycle that holds `v`. - **cost**: O(1) - **traps**: never Examples: - `domain V = 0..5; let nx: [V]V = [1, 2, 0, 0, 3]; let f = Functional(nx); f.root_of(4) == 0 and f.root_of(1) == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L2698) ### `Functional.depth` ```cp fn depth(self, v: V) -> Int ``` The steps from `v` to `root_of(v)`; `0` on a cycle. - **cost**: O(1) - **traps**: never Examples: - `domain V = 0..5; let nx: [V]V = [1, 2, 0, 0, 3]; let f = Functional(nx); f.depth(4) == 2 and f.depth(0) == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L2705) ### `Functional.cycle_len` ```cp fn cycle_len(self, v: V) -> Int ``` The length of the cycle `v` eventually reaches. - **cost**: O(1) - **traps**: never Examples: - `domain V = 0..5; let nx: [V]V = [1, 2, 0, 0, 3]; Functional(nx).cycle_len(4) == 3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L2712) ### `Functional.after` ```cp fn after(self, v: V, k: Int) -> V ``` The vertex `k` steps after `v`, by binary lifting: `after(v, 0) == v`. Never `None`, unlike `Rooted.ancestor`, since every vertex has an out-arc. - **cost**: O(log k) - **traps**: when `k < 0` Examples: - `domain V = 0..5; let nx: [V]V = [1, 2, 0, 0, 3]; let f = Functional(nx); f.after(4, 5) == 0 and f.after(4, 0) == 4` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L2720) ### `Functional.jump_while` ```cp fn jump_while(self, v: V, pred: V -> Bool) -> ?V ``` The first vertex `u` on the walk from `v`, `v` included, with `pred(u)`, or `None` if None appears. `pred` must be monotone along every walk (once true, true onward). - **cost**: O(log n) - **traps**: never Examples: - `domain V = 0..5; let nx: [V]V = [1, 2, 0, 0, 3]; let f = Functional(nx); f.jump_while(4, u => f.on_cycle(u)) == Some(0)` - `domain V = 0..5; let nx: [V]V = [1, 2, 0, 0, 3]; let f = Functional(nx); f.jump_while(0, u => u == 4) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L2735) ### `Functional.dist` ```cp fn dist(self, a: V, b: V) -> ?Int ``` The fewest steps from `a` to `b`, or `None` if the walk from `a` never reaches `b`; `dist(a, a) == Some(0)`. - **cost**: O(log n) - **traps**: never Examples: - `domain V = 0..5; let nx: [V]V = [1, 2, 0, 0, 3]; let f = Functional(nx); f.dist(4, 1) == Some(3) and f.dist(2, 0) == Some(1) and f.dist(1, 4) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L2752) ### `Functional.lift` ```cp fn lift(self, x: Int, k: Int) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L2763) ### `Functional.cycles` ```cp fn cycles(self) -> List> ``` Every cycle once, each in walk order from its smallest vertex. - **cost**: O(n) - **order**: cycles by smallest vertex - **traps**: never Examples: - `domain V = 0..5; let nx: [V]V = [1, 2, 0, 0, 3]; Functional(nx).cycles() == [[0, 1, 2]]` - `domain V = 0..3; let nx: [V]V = [0, 2, 1]; Functional(nx).cycles() == [[0], [1, 2]]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L2776) ## `IncrementalBridges` ```cp pub struct IncrementalBridges ``` O(log n) amortized per edge: 2-edge-connectivity under edge insertions. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L2791) ## `IncrementalBridges` ```cp impl IncrementalBridges ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L2794) ### `IncrementalBridges.new` ```cp fn new() -> IncrementalBridges ``` No edges yet: every vertex alone. - **cost**: O(n) - **traps**: never Examples: - `domain V = 0..2; var b = IncrementalBridges(); not b.same(V(0), V(1))` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L2800) ### `IncrementalBridges.add` ```cp fn add(mut self, u: V, v: V) ``` Adds the undirected edge `u - v`. A loop changes nothing; a parallel edge makes its ends two-edge-connected. - **cost**: O(log n) amortized - **traps**: never Examples: - `domain V = 0..2; var b = IncrementalBridges(); b.add(V(0), V(1)); b.add(V(0), V(1)); b.two_edge_same(V(0), V(1))` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L2808) ### `IncrementalBridges.two_edge_same` ```cp fn two_edge_same(mut self, u: V, v: V) -> Bool ``` Are `u` and `v` joined by two edge-disjoint paths? True for `u == v`. - **cost**: O(alpha) - **traps**: never Examples: - `domain V = 0..3; var b = IncrementalBridges(); b.add(V(0), V(1)); b.add(V(1), V(2)); let before = b.two_edge_same(V(0), V(2)); b.add(V(2), V(0)); not before and b.two_edge_same(V(0), V(2))` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L2815) ### `IncrementalBridges.same` ```cp fn same(mut self, u: V, v: V) -> Bool ``` Are `u` and `v` connected? - **cost**: O(alpha) - **traps**: never Examples: - `domain V = 0..3; var b = IncrementalBridges(); b.add(V(0), V(1)); b.add(V(1), V(2)); b.same(V(0), V(2))` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L2822) ## `Edge` ```cp pub struct Edge(e: E, u: V, v ``` O(1): one edge of a `Graph`: its id and its ends as given. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L2825) ## `Only` ```cp pub struct Only(g: G, keep: V -> Bool, from: V -> Bool) ``` `g.only(keep)`; see `only`. Implements every arc capability `G` has. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L2851) ### `Only.out` ```cp fn out(self, u: V) -> yields G.Arc ``` The arcs out of `u` the view keeps: None when `u` is dropped, else those whose `to` is kept. - **cost**: O(1) to make, O(1) per arc of `g` walked - **order**: arc order of `g` - **traps**: never Examples: - `domain V = 0..3; let g: [V]List = [[1, 2], [2], []]; g.only(keep: v => v != 1).out(0).collect() == [2]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L2859) ### `Only.deg` ```cp fn deg(self, u: V) -> Int ``` The number of arcs out of `u` the view keeps. - **cost**: O(deg u in `g`) - **traps**: never Examples: - `domain V = 0..3; let g: [V]List = [[1, 2], [2], []]; g.only(keep: v => v != 1).deg(0) == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L2869) ### `Only.transpose` ```cp fn transpose(self) -> Graph ``` The kept arcs reversed, built as a `Graph` (record arcs as `(..a, to: u)`, a plain vertex arc as `u`). - **cost**: O(n + m) - **traps**: never Examples: - `domain V = 0..3; let g: [V]List = [[1, 2], [2], []]; g.only(keep: v => v != 1).transpose().next(2).collect() == [0]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/graph.cp#L2880) --- # grid URL: /docs/ref/std/grid Generated from [spec/std/grid.cp](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/grid.cp) by `cpl doc --format json`. ## `Dir4` ```cp pub struct Dir4(k: Int) ``` One of the four directions up, right, down, left (clockwise, rows growing downwards). [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/grid.cp#L9) ### `Dir4.up` ```cp fn up() -> Dir4 ``` Up: one row towards row 0, delta `(-1, 0)`. - **cost**: O(1) - **traps**: never Examples: - `Dir4.up().delta == (-1, 0)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/grid.cp#L15) ### `Dir4.right` ```cp fn right() -> Dir4 ``` Right: one column higher, delta `(0, 1)`. - **cost**: O(1) - **traps**: never Examples: - `Dir4.right().delta == (0, 1)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/grid.cp#L21) ### `Dir4.down` ```cp fn down() -> Dir4 ``` Down: one row higher (rows grow downwards), delta `(1, 0)`. - **cost**: O(1) - **traps**: never Examples: - `Dir4.down().delta == (1, 0)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/grid.cp#L27) ### `Dir4.left` ```cp fn left() -> Dir4 ``` Left: one column lower, delta `(0, -1)`. - **cost**: O(1) - **traps**: never Examples: - `Dir4.left().delta == (0, -1)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/grid.cp#L33) ### `Dir4.all` ```cp fn all() -> List ``` All four directions, clockwise from up. The list is fresh each call, but has a fixed length of four, so the cost is constant. - **cost**: O(1) - **order**: up, right, down, left - **traps**: never Examples: - `Dir4.all() == [Dir4.up(), Dir4.right(), Dir4.down(), Dir4.left()]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/grid.cp#L41) ### `Dir4.from` ```cp fn from(letters: Str, ch: Char) -> ?Dir4 ``` The direction a letter stands for, given the letters for up, right, down and left in that Matching is exact (case-sensitive). If a letter appears more than once in `letters`, the first position wins. - **order**: `Dir4.from("URDL", ch)`, `Dir4.from("NESW", ch)`. `None` for another letter. - **cost**: O(1) - **ties**: a repeated letter maps to its first position in `letters` - **traps**: `letters.len != 4` Examples: - `Dir4.from("URDL", 'D') == Some(Dir4.down())` - `Dir4.from("NESW", 'W') == Some(Dir4.left())` - `Dir4.from("URDL", 'x') == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/grid.cp#L54) ### `Dir4.cw` ```cp fn cw(self) -> Dir4 ``` A quarter turn clockwise: up to right, right to down, down to left, left to up. - **cost**: O(1) - **traps**: never Examples: - `Dir4.up().cw == Dir4.right()` - `Dir4.left().cw == Dir4.up()` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/grid.cp#L64) ### `Dir4.ccw` ```cp fn ccw(self) -> Dir4 ``` A quarter turn counter-clockwise, the inverse of `cw`. - **cost**: O(1) - **traps**: never Examples: - `Dir4.up().ccw == Dir4.left()` - `Dir4.down().cw.ccw == Dir4.down()` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/grid.cp#L71) ### `Dir4.back` ```cp fn back(self) -> Dir4 ``` The opposite direction, a half turn: its delta is the negated delta. - **cost**: O(1) - **traps**: never Examples: - `Dir4.up().back == Dir4.down()` - `Dir4.right().back == Dir4.left()` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/grid.cp#L78) ### `Dir4.delta` ```cp fn delta(self) -> (Int, Int) ``` The change in (row, column) of one step. - **cost**: O(1) - **traps**: never Examples: - `Dir4.all().map(d => d.delta) == [(-1, 0), (0, 1), (1, 0), (0, -1)]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/grid.cp#L84) ## `Dir8` ```cp pub struct Dir8(k: Int) ``` One of the eight directions, clockwise from up: the four of `Dir4` and the diagonals between. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/grid.cp#L87) ### `Dir8.all` ```cp fn all() -> List ``` All eight directions, clockwise from up: up, up-right, right, down-right, down, down-left, left, up-left. `Dir8` has no named constructors; index this list. - **cost**: O(1) - **order**: clockwise from up - **traps**: never Examples: - `Dir8.all().map(d => d.delta) == [(-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1)]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/grid.cp#L95) ### `Dir8.from` ```cp fn from(letters: Str, ch: Char) -> ?Dir8 ``` The direction whose letter is `ch` in `letters`, listed in `Dir8.all()` order, e.g. `Dir8.from("NOEKSJWH", ch)` style alphabets. `None` for another letter. Matching is exact (case-sensitive). If a letter appears more than once in `letters`, the first position wins. - **cost**: O(1) - **ties**: a repeated letter maps to its first position in `letters` - **traps**: `letters.len != 8` Examples: - `Dir8.from("abcdefgh", 'c') == Some(Dir8.all()[2])` - `Dir8.from("abcdefgh", 'x') == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/grid.cp#L108) ### `Dir8.cw` ```cp fn cw(self) -> Dir8 ``` An eighth of a turn clockwise: the next direction in `Dir8.all()`, wrapping from up-left to up. - **cost**: O(1) - **traps**: never Examples: - `Dir8.all()[0].cw.delta == (-1, 1)` - `Dir8.all()[7].cw == Dir8.all()[0]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/grid.cp#L119) ### `Dir8.ccw` ```cp fn ccw(self) -> Dir8 ``` An eighth of a turn counter-clockwise, the inverse of `cw`. - **cost**: O(1) - **traps**: never Examples: - `Dir8.all()[0].ccw == Dir8.all()[7]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/grid.cp#L125) ### `Dir8.back` ```cp fn back(self) -> Dir8 ``` The opposite direction, four eighths round: its delta is the negated delta. - **cost**: O(1) - **traps**: never Examples: - `Dir8.all()[1].back.delta == (1, -1)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/grid.cp#L131) ### `Dir8.delta` ```cp fn delta(self) -> (Int, Int) ``` The change in (row, column) of one step; each part is `-1`, `0` or `1`. - **cost**: O(1) - **traps**: never Examples: - `Dir8.all()[3].delta == (1, 1)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/grid.cp#L137) --- # hashmap URL: /docs/ref/std/hashmap Generated from [spec/std/hashmap.cp](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/hashmap.cp) by `cpl doc --format json`. ## `FlatMap` ```cp pub struct FlatMap ``` Flat open-addressing hash map from `Int` keys to `V`, salted with `splitmix64`. `get`, `contains`, `set`, `remove`, and `get_or_insert` are O(1) expected. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/hashmap.cp#L11) ### `FlatMap.new` ```cp fn new(default_val: V, cap: Int = 16) -> FlatMap ``` [rename] Create an empty `FlatMap` sized for at least `cap` entries (replaces `with_capacity`). `default_val` fills the value slots that hold no entry; no method returns it, so any value of `V` works. The table is a power of two at least twice `cap`, so `cap` entries fit without a rehash; a `cap` below 1 gives the smallest table. - **cost**: O(cap) - **traps**: never Examples: - `var m: FlatMap = FlatMap(0); m.len == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/hashmap.cp#L29) ### `FlatMap.len` ```cp fn len(self) -> Int ``` Number of live key-value pairs. - **cost**: O(1) - **traps**: never Examples: - `var m = FlatMap(0); m.set(1, 5); m.set(1, 6); m.len == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/hashmap.cp#L39) ### `FlatMap.is_empty` ```cp fn is_empty(self) -> Bool ``` Whether the map has no live entries. - **cost**: O(1) - **traps**: never Examples: - `FlatMap(0).is_empty == true` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/hashmap.cp#L47) ### `FlatMap.clear` ```cp fn clear(mut self) ``` Remove all entries while keeping allocated capacity. - **cost**: O(capacity) - **traps**: never Examples: - `var m = FlatMap(0); m.set(1, 5); m.clear(); m.get(1) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/hashmap.cp#L55) ### `FlatMap.slot` ```cp fn slot(self, k: Int) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/hashmap.cp#L60) ### `FlatMap.rehash` ```cp fn rehash(mut self, new_cap: Int) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/hashmap.cp#L64) ### `FlatMap.get` ```cp fn get(self, k: Int) -> ?V ``` Look up `k`, returning `None` if absent. - **cost**: O(1) expected - **traps**: never Examples: - `var m = FlatMap(0); m.set(5, 50); m.get(5) == Some(50) and m.get(6) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/hashmap.cp#L82) ### `FlatMap.contains` ```cp fn contains(self, k: Int) -> Bool ``` Whether `k` is currently present. - **cost**: O(1) expected - **traps**: never Examples: - `var m = FlatMap(0); m.set(-3, 1); m.contains(-3) and not m.contains(3)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/hashmap.cp#L96) ### `FlatMap.set` ```cp fn set(mut self, k: Int, v: V) ``` Insert or overwrite `k -> v`. When the table would pass half full it doubles and every entry is rehashed. - **cost**: O(1) expected amortized - **traps**: never Examples: - `var m = FlatMap(0); m.set(1, 5); m.set(1, 6); m.get(1) == Some(6)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/hashmap.cp#L105) ### `FlatMap.get_or_insert` ```cp fn get_or_insert(mut self, k: Int, v: V) -> V ``` Return the value for `k`, inserting `v` first if `k` is absent. A present `k` keeps its value; `v` is then ignored. - **cost**: O(1) expected amortized - **traps**: never Examples: - `var m = FlatMap(0); m.get_or_insert(4, 7) == 7 and m.get_or_insert(4, 9) == 7` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/hashmap.cp#L133) ### `FlatMap.remove` ```cp fn remove(mut self, k: Int) -> ?V ``` Remove `k` if present; returns its old value or `None`. - **cost**: O(1) expected - **traps**: never Examples: - `var m = FlatMap(0); m.set(2, 9); m.remove(2) == Some(9) and m.remove(2) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/hashmap.cp#L143) ### `FlatMap.reserve` ```cp fn reserve(mut self, cap: Int) ``` Reserve space for at least `cap` entries without rehashing. Entries are kept; a `cap` the table already fits does nothing. - **cost**: O(cap) when the table grows, O(1) otherwise - **traps**: never Examples: - `var m = FlatMap(0); m.set(1, 2); m.reserve(1000); m.get(1) == Some(2)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/hashmap.cp#L162) ### `FlatMap.take` ```cp fn take(mut self) -> FlatMap ``` Move the map's contents out in O(1), leaving `self` empty. - **cost**: O(1) - **traps**: never Examples: - `var m = FlatMap(0); m.set(1, 2); let t = m.take(); m.is_empty and t.get(1) == Some(2)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/hashmap.cp#L172) ### `FlatMap.items` ```cp fn items(self) -> yields (Int, V) ``` O(1) to make. Yields every live `(key, val)` pair. The order is the table's slot order, which depends on the per-map salt: it is fixed while the map is unchanged and agrees with `keys` and `values`, but no program should depend on it. Sort when the order matters. - **cost**: O(1) to make, O(capacity) to walk - **empty**: yields nothing - **order**: unspecified slot order, the same as `keys` and `values` while unchanged - **traps**: never Examples: - `var m = FlatMap(0); m.set(2, 20); m.set(1, 10); m.items.sorted() == [(1, 10), (2, 20)]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/hashmap.cp#L192) ### `FlatMap.keys` ```cp fn keys(self) -> yields Int ``` - **cost**: O(1) to make, O(capacity) to walk - **empty**: yields nothing - **order**: unspecified slot order, the same as `items` - **traps**: never Examples: - `var m = FlatMap(0); m.set(2, 20); m.set(1, 10); m.keys.sorted() == [1, 2]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/hashmap.cp#L203) ### `FlatMap.values` ```cp fn values(self) -> yields V ``` - **cost**: O(1) to make, O(capacity) to walk - **empty**: yields nothing - **order**: unspecified slot order, the same as `items` - **traps**: never Examples: - `var m = FlatMap(0); m.set(2, 20); m.set(1, 10); m.values.sorted() == [10, 20]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/hashmap.cp#L214) ### `FlatMap.absorb` ```cp fn absorb(mut self, mut other: FlatMap, join: ?((V, V) -> V) = None) ``` Merge all entries from `other` into `self` (emptying `other`), combining collisions with `join` or overwriting. For a key in both maps the result is `join(self's value, other's value)`, or `other`'s value when `join` is `None`. The smaller map is drained into the larger, so the argument order of `join` and the overwrite rule hold whichever side is moved. - **cost**: O(min(|self|, |other|)) expected - **empty**: an empty `other` leaves `self` unchanged - **traps**: never Examples: - `var a = FlatMap(0); a.set(1, 10); var b = FlatMap(0); b.set(1, 5); b.set(2, 7); a.absorb(mut b, join: (x, y) => x + y); a.get(1) == Some(15) and a.get(2) == Some(7) and b.is_empty` - `var a = FlatMap(0); a.set(1, 10); var b = FlatMap(0); b.set(1, 5); a.absorb(mut b); a.get(1) == Some(5)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/hashmap.cp#L229) ## `Counter` ```cp pub struct Counter ``` Default-valued frequency / weight map over hashable keys `K`. `Counter` counts with `Int` (`V = Int`) and is a `Track` (`std.window`): `push(k)` adds 1, `pop(k)` takes 1 away. `c[k]` reads `init` without inserting; `add`, `get`, `set`, `remove`, and `contains` are O(1) expected. Invariant: no stored entry equals `init`. A write that leaves a key at `init` (`add`, `set`, `absorb`) removes it, so `len` is the number of keys whose value differs from `init` and `contains(k)` is `get(k) != init`. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/hashmap.cp#L247) ### `Counter.new` ```cp fn new(init: V) -> Counter ``` Create an empty `Counter` whose missing keys read as `init`. - **cost**: O(1) - **traps**: never Examples: - `var c: Counter = Counter(0); c.get('z') == 0 and c.len == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/hashmap.cp#L257) ### `Counter.of` ```cp fn of(xs: List) -> Counter ``` Count occurrences of each element in `xs`. The result has `init` `0`, so a key that never occurs reads `0`. - **cost**: O(n) expected - **empty**: an empty counter - **traps**: never Examples: - `let c = Counter.of(['a', 'b', 'a']); c.get('a') == 2 and c.get('c') == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/hashmap.cp#L268) ### `Counter.len` ```cp fn len(self) -> Int ``` Number of keys with a stored entry. - **cost**: O(1) - **traps**: never Examples: - `Counter.of([3, 1, 3]).len == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/hashmap.cp#L278) ### `Counter.is_empty` ```cp fn is_empty(self) -> Bool ``` Whether no keys are stored. - **cost**: O(1) - **traps**: never Examples: - `Counter.of([1]).is_empty == false` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/hashmap.cp#L286) ### `Counter.get` ```cp fn get(self, k: K) -> V ``` Value stored for `k`, or `init` if absent (does not insert). `c[k]` calls this. - **cost**: O(1) expected - **traps**: never Examples: - `let c = Counter.of([5, 5]); c[5] == 2 and c[6] == 0 and c.len == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/hashmap.cp#L296) ### `Counter.contains` ```cp fn contains(self, k: K) -> Bool ``` Whether `k` currently has a stored entry. - **cost**: O(1) expected - **traps**: never Examples: - `let c = Counter.of([5]); c.contains(5) and not c.contains(6)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/hashmap.cp#L305) ### `Counter.set` ```cp fn set(mut self, k: K, v: V) ``` Set `k` to `v` (W8 `IndexSet` backing `c[k] = v`). Setting a key to `init` removes it. - **cost**: O(1) expected amortized - **traps**: never Examples: - `var c = Counter.of(['a']); c['a'] = 4; c['a'] == 4` - `var c = Counter.of(['a']); c['a'] = 0; c.contains('a') == false` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/hashmap.cp#L316) ### `Counter.add` ```cp fn add(mut self, k: K, delta: V) ``` Add `delta` to `k`'s value, removing `k` if the result equals `init`. An absent key starts from `init`. `c[k] += d` is `c.add(k, d)`. - **cost**: O(1) expected amortized - **traps**: never (overflow wraps in release, traps in debug) Examples: - `var c: Counter = Counter(0); c.add('x', 2); c['x'] == 2` - `var c: Counter = Counter(0); c.add('x', 2); c.add('x', -2); c.len == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/hashmap.cp#L330) ### `Counter.remove` ```cp fn remove(mut self, k: K) -> ?V ``` Remove `k` and return its previous value, or `None` if absent. - **cost**: O(1) expected - **traps**: never Examples: - `var c = Counter.of(['a', 'a']); c.remove('a') == Some(2) and c.remove('a') == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/hashmap.cp#L338) ### `Counter.reserve` ```cp fn reserve(mut self, cap: Int) ``` Reserve space for at least `cap` keys. - **cost**: O(cap) when the table grows, O(1) otherwise - **traps**: never Examples: - `var c = Counter.of([1]); c.reserve(100); c[1] == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/hashmap.cp#L348) ### `Counter.clear` ```cp fn clear(mut self) ``` Remove all entries. - **cost**: O(n) - **traps**: never Examples: - `var c = Counter.of([1, 2]); c.clear(); c.len == 0 and c[1] == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/hashmap.cp#L356) ### `Counter.take` ```cp fn take(mut self) -> Counter ``` Move contents out in O(1), leaving `self` empty. The `init` of `self` is unchanged. - **cost**: O(1) - **traps**: never Examples: - `var c = Counter.of([1]); let d = c.take(); c.is_empty and d[1] == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/hashmap.cp#L366) ### `Counter.absorb` ```cp fn absorb(mut self, mut other: Counter) ``` Merge all entries from `other` into `self` by adding values (emptying `other`). Stored values are added: a key stored in both ends at the sum of the two, a key stored in one keeps that value, and a sum equal to `init` is removed. Absent keys contribute nothing (not `init`), which keeps the result the same whichever side is drained. - **cost**: O(min(|self|, |other|)) expected - **empty**: an empty `other` leaves `self` unchanged - **traps**: never (overflow wraps in release, traps in debug) Examples: - `var a = Counter.of(['x', 'y']); var b = Counter.of(['y', 'z']); a.absorb(mut b); a['y'] == 2 and a.len == 3 and b.len == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/hashmap.cp#L381) ### `Counter.total` ```cp fn total(self) -> V ``` Sum of all stored values. Only stored entries count; `init` is not added for absent keys. - **cost**: O(n) - **empty**: `V.zero` - **traps**: never (overflow wraps in release, traps in debug) Examples: - `Counter.of([1, 1, 2]).total() == 3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/hashmap.cp#L395) ### `Counter.most_common` ```cp fn most_common(self, k: Int) -> List<(K, V)> ``` Top `k` entries sorted by descending value. A `k` at least `len` returns every entry. - **cost**: O(n log n) - **empty**: `[]` - **ties**: equal values in ascending key order - **order**: descending value; a new `List`, keyed from 0 - **traps**: when `k < 0` Examples: - `Counter.of([3, 1, 3, 2, 1, 3]).most_common(2) == [(3, 3), (1, 2)]` - `Counter.of(['b', 'a']).most_common(5) == [('a', 1), ('b', 1)]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/hashmap.cp#L411) ### `Counter.items` ```cp fn items(self) -> yields (K, V) ``` O(1) to make. Yields every stored `(key, val)` pair. - **cost**: O(1) to make, O(1) per step - **empty**: yields nothing - **order**: unspecified hash order, the same as `keys` and `values` while unchanged - **traps**: never Examples: - `Counter.of([2, 1, 2]).items.sorted() == [(1, 1), (2, 2)]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/hashmap.cp#L427) ### `Counter.keys` ```cp fn keys(self) -> yields K ``` - **cost**: O(1) to make, O(1) per step - **empty**: yields nothing - **order**: unspecified hash order, the same as `items` - **traps**: never Examples: - `Counter.of([2, 1, 2]).keys.sorted() == [1, 2]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/hashmap.cp#L437) ### `Counter.values` ```cp fn values(self) -> yields V ``` - **cost**: O(1) to make, O(1) per step - **empty**: yields nothing - **order**: unspecified hash order, the same as `items` - **traps**: never Examples: - `Counter.of([2, 1, 2]).values.sorted() == [1, 2]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/hashmap.cp#L447) --- # heap URL: /docs/ref/std/heap Generated from [spec/std/heap.cp](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp) by `cpl doc --format json`. ## `Heap` ```cp pub struct Heap ``` A priority queue on `<`. `push` and `pop` are O(log n), `peek` is O(1); memory is one list. For a mixed order put `desc(x)` in the entry: `Heap<(Int, Desc)>()` pops the smallest distance first and, among equals, the largest vertex. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L13) ### `Heap.new` ```cp fn new(by: ?(T -> K) = None) -> Heap ``` Create an empty `Heap`, optionally ordered by key extractor `by:` (W7). With `by: f` the heap compares `f(x)`, and `f` is called on every comparison, so it should be cheap (a field, `desc`). Without `by:` it compares the elements themselves. - **cost**: O(1) - **traps**: never Examples: - `var h: Heap = Heap(); h.push(3); h.push(1); h.pop() == Some(1)` - `var h: Heap = Heap(by: desc); h.push(1); h.push(3); h.pop() == Some(3)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L26) ### `Heap.of` ```cp fn of(xs: List, by: ?(T -> K) = None) -> Heap ``` Build a `Heap` from `xs` via Floyd heapify. `by:` means what it means in `new`; without it pops come out in the order of `xs.sorted()`, and `Heap.of(xs, by: desc)` is the O(n) max-heap (`MaxHeap.of`). - **cost**: O(n) - **empty**: an empty heap - **traps**: never Examples: - `var h = Heap.of([3, 1, 2]); h.pop() == Some(1) and h.len == 2` - `var h = Heap.of([3, 1, 2], by: desc); h.pop() == Some(3)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L40) ### `Heap.len` ```cp fn len(self) -> Int ``` Number of elements currently in the heap. - **cost**: O(1) - **traps**: never Examples: - `Heap.of([3, 1]).len == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L54) ### `Heap.is_empty` ```cp fn is_empty(self) -> Bool ``` Whether the heap is empty. - **cost**: O(1) - **traps**: never Examples: - `Heap.of([3]).is_empty == false` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L61) ### `Heap.peek` ```cp fn peek(self) -> ?T ``` The smallest element, or `None` if the heap is empty. With `by: desc` the smallest key is the largest element. - **cost**: O(1) - **empty**: `None` - **traps**: never Examples: - `Heap.of([3, 1, 2]).peek == Some(1)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L72) ### `Heap.clear` ```cp fn clear(mut self) ``` Remove all elements from the heap. The order `by:` is kept. - **cost**: O(1) - **traps**: never Examples: - `var h = Heap.of([1, 2]); h.clear(); h.pop() == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L83) ### `Heap.take` ```cp fn take(mut self) -> Heap ``` Move the heap's contents out in O(1), leaving `self` empty. Both heaps keep the order `by:`. - **cost**: O(1) - **traps**: never Examples: - `var h = Heap.of([2, 1]); let t = h.take(); h.is_empty and t.peek == Some(1)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L93) ### `Heap.less` ```cp fn less(self, a: T, b: T) -> Bool ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L98) ### `Heap.sift_down` ```cp fn sift_down(mut self, start: Int) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L103) ### `Heap.push` ```cp fn push(mut self, x: T) ``` Push `x` into the heap. - **cost**: O(log n), amortized over list growth - **traps**: never Examples: - `var h = Heap.of([5]); h.push(2); h.peek == Some(2)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L120) ### `Heap.pop` ```cp fn pop(mut self) -> ?T ``` Remove and return the smallest element, or `None` if the heap is empty. - **cost**: O(log n) - **empty**: `None` - **traps**: never Examples: - `var h = Heap.of([2, 1]); h.pop() == Some(1) and h.pop() == Some(2) and h.pop() == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L136) ### `Heap.reserve` ```cp fn reserve(mut self, cap: Int) ``` Reserve backing storage for at least `cap` elements. - **cost**: O(cap) when the storage grows, O(1) otherwise - **traps**: never Examples: - `var h = Heap.of([2]); h.reserve(100); h.peek == Some(2)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L150) ### `Heap.push_pop` ```cp fn push_pop(mut self, x: T) -> T ``` Push `x` and pop the minimum in one sift. Returns `x` itself, leaving the heap unchanged, when the heap is empty or the key of `x` is no greater than the top's; otherwise returns the old top and keeps `x`. - **cost**: O(log n); O(1) when `x` is returned - **empty**: returns `x`; the heap stays empty - **traps**: never Examples: - `var h = Heap.of([2, 5]); h.push_pop(3) == 2 and h.peek == Some(3)` - `var h = Heap.of([2]); h.push_pop(1) == 1 and h.peek == Some(2)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L163) ### `Heap.replace_top` ```cp fn replace_top(mut self, x: T) -> ?T ``` Replace the minimum with `x` and return the old minimum (or `None` if empty). The old top is returned even when `x` is smaller than it. On an empty heap `x` is pushed and the result is `None`. - **cost**: O(log n) - **empty**: pushes `x` and returns `None` - **traps**: never Examples: - `var h = Heap.of([2, 5]); h.replace_top(9) == Some(2) and h.peek == Some(5)` - `var h: Heap = Heap(); h.replace_top(4) == None and h.peek == Some(4)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L180) ### `Heap.push_all` ```cp fn push_all(mut self, items: List) ``` Push all elements of `items`. - **cost**: O(k log n) for `k` items - **empty**: an empty `items` does nothing - **traps**: never Examples: - `var h = Heap.of([4]); h.push_all([3, 1]); h.peek == Some(1) and h.len == 3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L195) ### `Heap.drain` ```cp fn drain(mut self) -> yields T ``` Pop and yield all elements in ascending order, leaving the heap empty. Each step is one `pop`. A loop that stops early leaves the elements not yet yielded in the heap. - **cost**: O(log n) per step - **empty**: yields nothing - **order**: ascending key order, the order `pop` would return them - **traps**: never Examples: - `var h = Heap.of([3, 1, 2]); h.drain().collect() == [1, 2, 3] and h.is_empty` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L208) ## `ErasableHeap` ```cp pub struct ErasableHeap ``` Min-heap supporting O(log n) arbitrary-value `remove(x)` via a lazy deletion heap. `push` and `remove` are O(log n); `peek` and `pop` are O(log n) amortized; `len`, `is_empty`, `clear`, and `take` are O(1). [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L214) ### `ErasableHeap.new` ```cp fn new(by: ?(T -> K) = None) -> ErasableHeap ``` Create an empty `ErasableHeap`, optionally ordered by key extractor `by:` (W7). - **cost**: O(1) - **traps**: never Examples: - `var h: ErasableHeap = ErasableHeap(); h.push(2); h.push(1); h.remove(1); h.pop() == Some(2)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L223) ### `ErasableHeap.len` ```cp fn len(self) -> Int ``` Number of active elements in the heap. Pushed elements minus removed ones, counting copies. - **cost**: O(1) - **traps**: never Examples: - `var h: ErasableHeap = ErasableHeap(); h.push(1); h.push(1); h.remove(1); h.len == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L233) ### `ErasableHeap.is_empty` ```cp fn is_empty(self) -> Bool ``` Whether no active elements remain. - **cost**: O(1) - **traps**: never Examples: - `var h: ErasableHeap = ErasableHeap(); h.push(1); h.remove(1); h.is_empty` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L241) ### `ErasableHeap.clear` ```cp fn clear(mut self) ``` Remove all elements from the heap. - **cost**: O(1) - **traps**: never Examples: - `var h: ErasableHeap = ErasableHeap(); h.push(1); h.clear(); h.pop() == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L249) ### `ErasableHeap.take` ```cp fn take(mut self) -> ErasableHeap ``` Move the heap's contents out in O(1), leaving `self` empty. Pending removals move with the contents. - **cost**: O(1) - **traps**: never Examples: - `var h: ErasableHeap = ErasableHeap(); h.push(1); let t = h.take(); h.is_empty and t.len == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L260) ### `ErasableHeap.prune` ```cp fn prune(mut self) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L264) ### `ErasableHeap.push` ```cp fn push(mut self, x: T) ``` Push `x` into the heap. - **cost**: O(log n) - **traps**: never Examples: - `var h: ErasableHeap = ErasableHeap(); h.push(4); h.peek() == Some(4)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L277) ### `ErasableHeap.remove` ```cp fn remove(mut self, x: T) ``` Schedule one copy of `x` for lazy removal (`x` must be present). One copy goes, even when several are present. The copy leaves at once as far as `len`, `peek` and `pop` can see; its storage is freed when it would reach the top. Removing a value that is not present corrupts the heap: debug builds trap when they find such a value surfacing. - **cost**: O(log n) - **traps**: never in release; debug traps when `x` is found not to be present Examples: - `var h: ErasableHeap = ErasableHeap(); h.push(1); h.push(1); h.push(3); h.remove(1); h.pop() == Some(1) and h.pop() == Some(3)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L290) ### `ErasableHeap.peek` ```cp fn peek(mut self) -> ?T ``` Return the smallest active element, or `None` if empty. Takes `mut self` because it first discards removed values sitting on top. - **cost**: O(log n) amortized - **empty**: `None` - **traps**: never Examples: - `var h: ErasableHeap = ErasableHeap(); h.push(1); h.push(2); h.remove(1); h.peek() == Some(2)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L301) ### `ErasableHeap.pop` ```cp fn pop(mut self) -> ?T ``` Remove and return the smallest active element, or `None` if empty. - **cost**: O(log n) amortized - **empty**: `None` - **traps**: never Examples: - `var h: ErasableHeap = ErasableHeap(); h.push(5); h.push(2); h.pop() == Some(2) and h.len == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L311) ## `IndexedHeap` ```cp pub struct IndexedHeap ``` Domain-keyed min-heap over `D` supporting O(log n) `set`, `decrease`, `increase`, `remove`, and `pop`, plus O(1) `contains`, `get`, and `peek`. Each `v: D` is in the heap at most once, with one key `K`. Ties between equal keys go to the smaller `v` in `D`'s order, so the pop order is fully determined. Memory is O(|D|). [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L320) ### `IndexedHeap.new` ```cp fn new() -> IndexedHeap ``` Create an empty `IndexedHeap`. - **cost**: O(|D|) - **traps**: never Examples: - `domain V = 0..4; var h: IndexedHeap = IndexedHeap(); h.len == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L330) ### `IndexedHeap.len` ```cp fn len(self) -> Int ``` Number of keys currently in the heap. - **cost**: O(1) - **traps**: never Examples: - `domain V = 0..4; var h: IndexedHeap = IndexedHeap(); h.set(V(1), 5); h.set(V(1), 6); h.len == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L338) ### `IndexedHeap.is_empty` ```cp fn is_empty(self) -> Bool ``` Whether the heap is empty. - **cost**: O(1) - **traps**: never Examples: - `domain V = 0..4; var h: IndexedHeap = IndexedHeap(); h.is_empty` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L346) ### `IndexedHeap.contains` ```cp fn contains(self, v: D) -> Bool ``` Whether `v` is currently in the heap. - **cost**: O(1) - **traps**: never Examples: - `domain V = 0..4; var h: IndexedHeap = IndexedHeap(); h.set(V(2), 5); h.contains(V(2)) and not h.contains(V(3))` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L354) ### `IndexedHeap.get` ```cp fn get(self, v: D) -> ?K ``` Current priority of `v`, or `None` if absent. - **cost**: O(1) - **traps**: never Examples: - `domain V = 0..4; var h: IndexedHeap = IndexedHeap(); h.set(V(2), 5); h.get(V(2)) == Some(5) and h.get(V(0)) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L362) ### `IndexedHeap.peek` ```cp fn peek(self) -> ?(D, K) ``` Pair `(v, key)` with the smallest key, or `None` if empty. - **cost**: O(1) - **empty**: `None` - **traps**: never Examples: - `domain V = 0..4; var h: IndexedHeap = IndexedHeap(); h.set(V(3), 1); h.set(V(1), 1); h.peek == Some((V(1), 1))` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L371) ### `IndexedHeap.clear` ```cp fn clear(mut self) ``` Remove all entries from the heap. - **cost**: O(len) - **traps**: never Examples: - `domain V = 0..4; var h: IndexedHeap = IndexedHeap(); h.set(V(1), 5); h.clear(); h.get(V(1)) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L381) ### `IndexedHeap.before` ```cp fn before(self, a: D, b: D) -> Bool ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L387) ### `IndexedHeap.swap_at` ```cp fn swap_at(mut self, i: Int, j: Int) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L392) ### `IndexedHeap.sift_up` ```cp fn sift_up(mut self, start: Int) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L400) ### `IndexedHeap.sift_down` ```cp fn sift_down(mut self, start: Int) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L408) ### `IndexedHeap.set` ```cp fn set(mut self, v: D, k: K) ``` Insert `v` with key `k`, or update `v`'s key to `k`. The new key may be larger or smaller than the old one. - **cost**: O(log n) - **traps**: never Examples: - `domain V = 0..4; var h: IndexedHeap = IndexedHeap(); h.set(V(1), 5); h.set(V(1), 9); h.get(V(1)) == Some(9)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L425) ### `IndexedHeap.decrease` ```cp fn decrease(mut self, v: D, k: K) -> Bool ``` Insert `v` with `k`, or lower its key to `k` if `k` is smaller. Returns `true` if updated. The relaxation step of Dijkstra. An equal key is not smaller: it returns `false`. - **cost**: O(log n) - **traps**: never Examples: - `domain V = 0..4; var h: IndexedHeap = IndexedHeap(); h.decrease(V(1), 5) and not h.decrease(V(1), 5) and h.decrease(V(1), 3) and h.get(V(1)) == Some(3)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L442) ### `IndexedHeap.increase` ```cp fn increase(mut self, v: D, k: K) -> Bool ``` Insert `v` with `k`, or raise its key to `k` if `k` is larger. Returns `true` if updated. An equal key is not larger: it returns `false`. - **cost**: O(log n) - **traps**: never Examples: - `domain V = 0..4; var h: IndexedHeap = IndexedHeap(); h.increase(V(1), 5) and not h.increase(V(1), 2) and h.get(V(1)) == Some(5)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L455) ### `IndexedHeap.remove` ```cp fn remove(mut self, v: D) -> ?K ``` Remove `v` from the heap if present; returns its old key or `None`. - **cost**: O(log n) - **traps**: never Examples: - `domain V = 0..4; var h: IndexedHeap = IndexedHeap(); h.set(V(1), 5); h.remove(V(1)) == Some(5) and h.remove(V(1)) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L466) ### `IndexedHeap.pop` ```cp fn pop(mut self) -> ?(D, K) ``` Remove and return `(v, key)` with the smallest key, or `None` if empty. - **cost**: O(log n) - **empty**: `None` - **traps**: never Examples: - `domain V = 0..4; var h: IndexedHeap = IndexedHeap(); h.set(V(2), 5); h.set(V(0), 7); h.pop() == Some((V(2), 5)) and h.len == 1` - `domain V = 0..4; var h: IndexedHeap = IndexedHeap(); h.set(V(3), 1); h.set(V(1), 1); h.pop() == Some((V(1), 1))` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L487) ## `MinMaxHeap` ```cp pub struct MinMaxHeap ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L499) ### `MinMaxHeap.new` ```cp fn new(by: ?(T -> K) = None) -> MinMaxHeap ``` Create an empty `MinMaxHeap`, optionally ordered by key extractor `by:` (W7). - **cost**: O(1) - **traps**: never Examples: - `var h: MinMaxHeap = MinMaxHeap(); h.push(2); h.push(7); h.first == Some(2) and h.last == Some(7)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L508) ### `MinMaxHeap.of` ```cp fn of(xs: List) -> MinMaxHeap ``` Build a `MinMaxHeap` from `xs` in linear time. The heap orders the elements themselves (there is no `by:`). - **cost**: O(n) - **empty**: an empty heap - **traps**: never Examples: - `var h = MinMaxHeap.of([3, 1, 4, 1, 5]); h.pop_last() == Some(5) and h.pop_first() == Some(1) and h.first == Some(1)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L520) ### `MinMaxHeap.reserve` ```cp fn reserve(mut self, cap: Int) ``` Reserve backing storage for at least `cap` elements. - **cost**: O(cap) when the storage grows, O(1) otherwise - **traps**: never Examples: - `var h = MinMaxHeap.of([2]); h.reserve(100); h.first == Some(2)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L533) ### `MinMaxHeap.len` ```cp fn len(self) -> Int ``` Number of elements currently in the heap. - **cost**: O(1) - **traps**: never Examples: - `MinMaxHeap.of([1, 1]).len == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L541) ### `MinMaxHeap.is_empty` ```cp fn is_empty(self) -> Bool ``` Whether the heap is empty. - **cost**: O(1) - **traps**: never Examples: - `MinMaxHeap.of([1]).is_empty == false` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L549) ### `MinMaxHeap.first` ```cp fn first(self) -> ?T ``` The smallest element, or `None` if empty. With one element, `first` and `last` are the same element. - **cost**: O(1) - **empty**: `None` - **ties**: unspecified among equal keys under `by:`; `pop_first` returns the one shown - **traps**: never Examples: - `MinMaxHeap.of([3, 1, 2]).first == Some(1)` - `MinMaxHeap.of([7]).first == Some(7)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L562) ### `MinMaxHeap.last` ```cp fn last(self) -> ?T ``` The largest element, or `None` if empty. - **cost**: O(1) - **empty**: `None` - **ties**: unspecified among equal keys under `by:`; `pop_last` returns the one shown - **traps**: never Examples: - `MinMaxHeap.of([3, 1, 2]).last == Some(3)` - `MinMaxHeap.of([7]).last == Some(7)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L574) ### `MinMaxHeap.push` ```cp fn push(mut self, x: T) ``` Insert `x`. - **cost**: O(log n), amortized over list growth - **traps**: never Examples: - `var h = MinMaxHeap.of([2, 5]); h.push(9); h.last == Some(9) and h.first == Some(2)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L583) ### `MinMaxHeap.pop_first` ```cp fn pop_first(mut self) -> ?T ``` Remove and return the smallest element, or `None` if empty. - **cost**: O(log n) - **empty**: `None` - **traps**: never Examples: - `var h = MinMaxHeap.of([2, 5, 3]); h.pop_first() == Some(2) and h.first == Some(3)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L605) ### `MinMaxHeap.pop_last` ```cp fn pop_last(mut self) -> ?T ``` Remove and return the largest element, or `None` if empty. - **cost**: O(log n) - **empty**: `None` - **traps**: never Examples: - `var h = MinMaxHeap.of([2, 5, 3]); h.pop_last() == Some(5) and h.last == Some(3)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L617) ### `MinMaxHeap.clear` ```cp fn clear(mut self) ``` Remove all elements. - **cost**: O(1) - **traps**: never Examples: - `var h = MinMaxHeap.of([2]); h.clear(); h.first == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L629) ### `MinMaxHeap.take` ```cp fn take(mut self) -> MinMaxHeap ``` Move contents out in O(1), leaving `self` empty. - **cost**: O(1) - **traps**: never Examples: - `var h = MinMaxHeap.of([2]); let t = h.take(); h.is_empty and t.first == Some(2)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L637) ### `MinMaxHeap.less` ```cp fn less(self, a: T, b: T) -> Bool ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L642) ### `MinMaxHeap.swap` ```cp fn swap(mut self, i: Int, j: Int) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L646) ### `MinMaxHeap.max_at` ```cp fn max_at(self) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L651) ### `MinMaxHeap.bubble_up` ```cp fn bubble_up(mut self, start: Int, min_side: Bool) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L655) ### `MinMaxHeap.remove_at` ```cp fn remove_at(mut self, i: Int) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L664) ### `MinMaxHeap.trickle_down` ```cp fn trickle_down(mut self, start: Int) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L670) ## `MeldHeap` ```cp pub struct MeldHeap ``` Meldable min-heap (skew / leftist heap) with O(log n) `meld` and O(1) lazy offset `add_all`. `peek` / `top` is O(1); `push`, `pop`, and `meld` are O(log n). [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L692) ### `MeldHeap.new` ```cp fn new(by: ?(T -> K) = None) -> MeldHeap ``` Create an empty `MeldHeap`, optionally ordered by key extractor `by:` (W7). - **cost**: O(1) - **traps**: never Examples: - `var h: MeldHeap = MeldHeap(); h.push(3); h.push(1); h.pop() == Some(1)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L706) ### `MeldHeap.of` ```cp fn of(xs: List) -> MeldHeap ``` Build a `MeldHeap` from `xs`. The heap orders the elements themselves (there is no `by:`). - **cost**: O(n) - **empty**: an empty heap - **traps**: never Examples: - `MeldHeap.of([4, 2, 3]).peek == Some(2)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L718) ### `MeldHeap.len` ```cp fn len(self) -> Int ``` Number of elements currently in the heap. - **cost**: O(1) - **traps**: never Examples: - `MeldHeap.of([4, 2]).len == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L734) ### `MeldHeap.is_empty` ```cp fn is_empty(self) -> Bool ``` Whether the heap is empty. - **cost**: O(1) - **traps**: never Examples: - `MeldHeap.of([4]).is_empty == false` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L741) ### `MeldHeap.peek` ```cp fn peek(self) -> ?T ``` The smallest element, or `None` if empty. The value includes every `add_all` applied since it was pushed. - **cost**: O(1) - **empty**: `None` - **traps**: never Examples: - `var h = MeldHeap.of([4, 2]); h.add_all(1); h.peek == Some(3)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L751) ### `MeldHeap.top` ```cp fn top(self) -> ?T ``` The smallest element, or `None` if empty (alias for `peek`). see: `peek` - **cost**: O(1) - **empty**: `None` - **ties**: as `peek`: unspecified among equal keys under `by:` - **traps**: never Examples: - `MeldHeap.of([4, 2]).top == Some(2)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L761) ### `MeldHeap.push` ```cp fn push(mut self, x: T) ``` Push `x` into the heap. `x` is stored as given: earlier `add_all` offsets do not apply to it. - **cost**: O(log n) - **traps**: never Examples: - `var h = MeldHeap.of([1, 5]); h.add_all(10); h.push(3); h.drain() == [3, 11, 15]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L770) ### `MeldHeap.push_all` ```cp fn push_all(mut self, items: List) ``` Push all elements of `items`. - **cost**: O(k log n) for `k` items - **empty**: an empty `items` does nothing - **traps**: never Examples: - `var h = MeldHeap.of([4]); h.push_all([3, 1]); h.drain() == [1, 3, 4]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L781) ### `MeldHeap.pop` ```cp fn pop(mut self) -> ?T ``` Remove and return the smallest element, or `None` if empty. - **cost**: O(log n) - **empty**: `None` - **traps**: never Examples: - `var h = MeldHeap.of([4, 2]); h.pop() == Some(2) and h.pop() == Some(4) and h.pop() == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L790) ### `MeldHeap.meld` ```cp fn meld(mut self, other: MeldHeap) ``` Meld `other` into `self` (consuming `other`). Every element keeps the value its own heap reported: pending `add_all` offsets apply only to the elements they were added to. - **cost**: O(log n) - **traps**: never Examples: - `var a = MeldHeap.of([4, 2]); a.meld(MeldHeap.of([3, 1])); a.drain() == [1, 2, 3, 4]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L807) ### `MeldHeap.absorb` ```cp fn absorb(mut self, mut other: MeldHeap) ``` Meld `other` into `self`, leaving `other` empty. `meld` for an `other` you keep using: small-to-large merging over a tree. - **cost**: O(log n) - **traps**: never Examples: - `var a = MeldHeap.of([4]); var b = MeldHeap.of([1]); a.absorb(mut b); a.peek == Some(1) and b.is_empty` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L826) ### `MeldHeap.add_all` ```cp fn add_all(mut self, delta: T) ``` Add `delta` lazily to every element (for additive types). Only the elements in the heap now change; later pushes do not. Adding one value to every element keeps their order; with `by:`, the key must keep that order too, or later pops are unspecified. - **cost**: O(1) - **empty**: does nothing - **traps**: never (overflow wraps in release, traps in debug) Examples: - `var h = MeldHeap.of([1, 5]); h.add_all(10); h.pop() == Some(11)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L840) ### `MeldHeap.clear` ```cp fn clear(mut self) ``` Remove all elements. - **cost**: O(1) - **traps**: never Examples: - `var h = MeldHeap.of([1]); h.clear(); h.pop() == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L850) ### `MeldHeap.take` ```cp fn take(mut self) -> MeldHeap ``` Move contents out in O(1), leaving `self` empty. - **cost**: O(1) - **traps**: never Examples: - `var h = MeldHeap.of([1]); let t = h.take(); h.is_empty and t.peek == Some(1)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L863) ### `MeldHeap.drain` ```cp fn drain(mut self) -> List ``` Pop and return all elements in ascending order, leaving `self` empty. - **cost**: O(n log n) - **empty**: `[]` - **order**: ascending key order, the order `pop` would return them; a new `List`, keyed from 0 - **traps**: never Examples: - `var h = MeldHeap.of([3, 1, 2]); h.drain() == [1, 2, 3] and h.is_empty` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L875) ### `MeldHeap.less` ```cp fn less(self, a: T, b: T) -> Bool ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L880) ### `MeldHeap.node` ```cp fn node(mut self, x: T) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L884) ### `MeldHeap.rank_of` ```cp fn rank_of(self, t: Int) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L891) ### `MeldHeap.push_down` ```cp fn push_down(mut self, t: Int) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L894) ### `MeldHeap.merge` ```cp fn merge(mut self, a: Int, b: Int) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L903) ## `MinHeap` ```cp pub type MinHeap = Heap ``` `Heap()`: pops the smallest first. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L976) ## `MaxHeap` ```cp pub struct MaxHeap ``` `Heap(by: desc)` under its own name: pops the largest first, with the same operations and costs as `Heap`; it holds each element as `desc(x)`. For a mixed order use `Heap` with `desc(x)` in the entry. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L980) ### `MaxHeap.new` ```cp fn new() -> MaxHeap ``` An empty `MaxHeap`. - **cost**: O(1) - **traps**: never Examples: - `var h = MaxHeap(); h.push(1); h.push(3); h.pop() == Some(3)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L988) ### `MaxHeap.of` ```cp fn of(xs: List) -> MaxHeap ``` Build a `MaxHeap` from `xs` via Floyd heapify. - **cost**: O(n) - **empty**: an empty heap - **traps**: never Examples: - `var h = MaxHeap.of([3, 1, 2]); h.pop() == Some(3) and h.len == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L996) ### `MaxHeap.len` ```cp fn len(self) -> Int ``` Number of elements currently in the heap. - **cost**: O(1) - **traps**: never Examples: - `MaxHeap.of([3, 1]).len == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L1003) ### `MaxHeap.is_empty` ```cp fn is_empty(self) -> Bool ``` Whether the heap is empty. - **cost**: O(1) - **traps**: never Examples: - `MaxHeap.of([3]).is_empty == false` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L1010) ### `MaxHeap.peek` ```cp fn peek(self) -> ?T ``` The largest element, or `None` when empty. - **cost**: O(1) - **traps**: never Examples: - `MaxHeap.of([3, 9, 2]).peek == Some(9)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L1017) ### `MaxHeap.clear` ```cp fn clear(mut self) ``` Remove every element. - **cost**: O(1) - **traps**: never Examples: - `var h = MaxHeap.of([2]); h.clear(); h.is_empty` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L1026) ### `MaxHeap.take` ```cp fn take(mut self) -> MaxHeap ``` Move the contents out, leaving this heap empty. - **cost**: O(1) - **traps**: never Examples: - `var h = MaxHeap.of([2, 7]); let t = h.take(); h.is_empty and t.peek == Some(7)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L1034) ### `MaxHeap.push` ```cp fn push(mut self, x: T) ``` Add `x`. - **cost**: O(log n) - **traps**: never Examples: - `var h = MaxHeap.of([2]); h.push(5); h.peek == Some(5)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L1041) ### `MaxHeap.pop` ```cp fn pop(mut self) -> ?T ``` Remove and return the largest element, or `None` when empty. - **cost**: O(log n) - **traps**: never Examples: - `var h = MaxHeap.of([4, 9]); h.pop() == Some(9) and h.pop() == Some(4) and h.pop() == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L1049) ### `MaxHeap.reserve` ```cp fn reserve(mut self, cap: Int) ``` Make room for `cap` elements in total. - **cost**: O(cap) when the storage grows, O(1) otherwise - **traps**: never Examples: - `var h = MaxHeap.of([2]); h.reserve(100); h.peek == Some(2)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L1058) ### `MaxHeap.push_pop` ```cp fn push_pop(mut self, x: T) -> T ``` Push `x`, then pop and return the largest element. - **cost**: O(log n); O(1) when `x` is returned - **traps**: never Examples: - `var h = MaxHeap.of([4]); h.push_pop(7) == 7 and h.peek == Some(4)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L1066) ### `MaxHeap.replace_top` ```cp fn replace_top(mut self, x: T) -> ?T ``` Pop the largest element, then push `x`; returns the popped one, or `None` (and only pushes) when empty. - **cost**: O(log n) - **traps**: never Examples: - `var h = MaxHeap.of([4]); h.replace_top(1) == Some(4) and h.peek == Some(1)` - `var h = MaxHeap(); h.replace_top(4) == None and h.peek == Some(4)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L1075) ### `MaxHeap.push_all` ```cp fn push_all(mut self, items: List) ``` Push every element of `items`. - **cost**: O(n + k log(n + k)) - **empty**: changes nothing - **traps**: never Examples: - `var h = MaxHeap(); h.push_all([3, 8]); h.peek == Some(8)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L1085) ### `MaxHeap.drain` ```cp fn drain(mut self) -> yields T ``` Pop every element, largest first. - **cost**: O(n log n) - **empty**: yields nothing - **traps**: never Examples: - `var h = MaxHeap.of([1, 3, 2]); h.drain().collect() == [3, 2, 1]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L1094) ## `Settle` ```cp pub struct Settle(best: (P, P) -> P = min) ``` A keyed frontier where each key pops exactly once. `offer(k, p)` keeps the best priority seen for a key that has not popped yet and is ignored after it has; `pop` returns the best key and settles it. The shape of Dijkstra, Prim and "settle answers from the largest down", without a side array of done flags or a lazy-deletion `continue`. O(log n) per offer and pop. `best` picks the better of two priorities and must return one of its arguments, like `min` and `max`; with any other function the popped priorities are unspecified. Keys are hashed. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L1104) ### `Settle.better` ```cp fn better(self, a: Int, b: Int) -> Bool ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L1109) ### `Settle.sift_up` ```cp fn sift_up(mut self, i0: Int) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L1113) ### `Settle.sift_down` ```cp fn sift_down(mut self) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L1119) ### `Settle.offer` ```cp fn offer(mut self, k: K, p: P) ``` Offer priority `p` for key `k`: an unsettled key keeps `best(old, p)` (or `p` when it had None); a settled key ignores the offer. - **cost**: O(log n) amortized, `n` the offers so far - **traps**: never Examples: - `var s: Settle = Settle(); s.offer('a', 5); s.offer('a', 2); s.offer('a', 4); s.get('a') == Some(2)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L1135) ### `Settle.pop` ```cp fn pop(mut self) -> ?(K, P) ``` Settle and return the unsettled key whose priority is best, with that priority, or `None` when every offered key has settled. - **cost**: O(log n) amortized, `n` the offers so far - **empty**: `None` - **ties**: unspecified among keys with equal priorities, as in `Heap` - **traps**: never Examples: - `var s: Settle = Settle(); s.offer('a', 5); s.offer('b', 3); s.pop() == Some(('b', 3)) and s.settled('b')` - `var s: Settle = Settle(); s.offer('b', 3); s.pop(); s.offer('b', 1); s.pop() == None` - `var s: Settle = Settle(best: max); s.offer('a', 5); s.offer('b', 3); s.pop() == Some(('a', 5))` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L1155) ### `Settle.settled` ```cp fn settled(self, k: K) -> Bool ``` Whether `k` has popped. - **cost**: O(1) expected - **traps**: never Examples: - `var s: Settle = Settle(); s.offer('a', 1); not s.settled('a') and s.pop() == Some(('a', 1)) and s.settled('a')` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L1170) ### `Settle.get` ```cp fn get(self, k: K) -> ?P ``` The best priority offered for `k` so far (for a settled key, the one it popped with), or `None` if `k` was never offered. - **cost**: O(1) expected - **traps**: never Examples: - `var s: Settle = Settle(); s.offer('a', 4); s.get('a') == Some(4) and s.get('b') == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/heap.cp#L1177) --- # Library URL: /docs/ref/std Generated from `spec/std` by `cpl doc --format json`. Costs and traps follow the [doc standard](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/README.md). ## Modules - [algebra](/docs/ref/std/algebra) (46 items) - [bag](/docs/ref/std/bag) (15 items) - [beats](/docs/ref/std/beats) (3 items) - [bitset](/docs/ref/std/bitset) (18 items) - [deque](/docs/ref/std/deque) (6 items) - [dp](/docs/ref/std/dp) (28 items) - [dsu](/docs/ref/std/dsu) (17 items) - [fenwick](/docs/ref/std/fenwick) (11 items) - [flow](/docs/ref/std/flow) (50 items) - [geometry](/docs/ref/std/geometry) (175 items) - [graph](/docs/ref/std/graph) (102 items) - [grid](/docs/ref/std/grid) (9 items) - [hashmap](/docs/ref/std/hashmap) (6 items) - [heap](/docs/ref/std/heap) (15 items) - [interval](/docs/ref/std/interval) (7 items) - [io](/docs/ref/std/io) (4 items) - [lazy](/docs/ref/std/lazy) (22 items) - [marks](/docs/ref/std/marks) (13 items) - [math](/docs/ref/std/math) (97 items) - [matrix](/docs/ref/std/matrix) (23 items) - [mod](/docs/ref/std/mod) (21 items) - [ntt](/docs/ref/std/ntt) (28 items) - [pair](/docs/ref/std/pair) (2 items) - [persistent](/docs/ref/std/persistent) (7 items) - [poly](/docs/ref/std/poly) (49 items) - [prefix](/docs/ref/std/prefix) (18 items) - [rand](/docs/ref/std/rand) (1 items) - [segtree](/docs/ref/std/segtree) (17 items) - [seq](/docs/ref/std/seq) (199 items) - [slope](/docs/ref/std/slope) (6 items) - [sparse](/docs/ref/std/sparse) (9 items) - [strings](/docs/ref/std/strings) (100 items) - [subset](/docs/ref/std/subset) (5 items) - [timetree](/docs/ref/std/timetree) (6 items) - [tree](/docs/ref/std/tree) (54 items) - [window](/docs/ref/std/window) (14 items) ## A to Z | Item | Module | Cost | | --- | --- | --- | | `Action` | [algebra](/docs/ref/std/algebra) | | | `Action.new` | [algebra](/docs/ref/std/algebra) | O(1) | | `Action.of` | [algebra](/docs/ref/std/algebra) | O(1) | | `AddAction` | [algebra](/docs/ref/std/algebra) | | | `Affine` | [algebra](/docs/ref/std/algebra) | | | `Affine.eval` | [algebra](/docs/ref/std/algebra) | O(1) | | `Affine.id` | [algebra](/docs/ref/std/algebra) | O(1) | | `Affine.monoid` | [algebra](/docs/ref/std/algebra) | O(1) | | `Affine.then` | [algebra](/docs/ref/std/algebra) | O(1) | | `AffineAction` | [algebra](/docs/ref/std/algebra) | | | `AhoCorasick` | [strings](/docs/ref/std/strings) | | | `AhoCorasick.counts` | [strings](/docs/ref/std/strings) | | | `AhoCorasick.exit_link` | [strings](/docs/ref/std/strings) | O(1) | | `AhoCorasick.fail_order` | [strings](/docs/ref/std/strings) | O(states) | | `AhoCorasick.find_all` | [strings](/docs/ref/std/strings) | | | `AhoCorasick.hit` | [strings](/docs/ref/std/strings) | | | `AhoCorasick.len` | [strings](/docs/ref/std/strings) | O(1) | | `AhoCorasick.link` | [strings](/docs/ref/std/strings) | | | `AhoCorasick.new` | [strings](/docs/ref/std/strings) | | | `AhoCorasick.pattern_state` | [strings](/docs/ref/std/strings) | O(1) | | `AhoCorasick.root` | [strings](/docs/ref/std/strings) | O(1) | | `AhoCorasick.step` | [strings](/docs/ref/std/strings) | | | `AhoCorasick.words_at` | [strings](/docs/ref/std/strings) | | | `Anchor` | [seq](/docs/ref/std/seq) | | | `Arc` | [flow](/docs/ref/std/flow) | | | `Arc.rev` | [flow](/docs/ref/std/flow) | O(1) | | `Arena` | [marks](/docs/ref/std/marks) | | | `Arena.alloc` | [marks](/docs/ref/std/marks) | O(1) amortized | | `Arena.clear` | [marks](/docs/ref/std/marks) | O(1) | | `Arena.get` | [marks](/docs/ref/std/marks) | O(1) | | `Arena.is_empty` | [marks](/docs/ref/std/marks) | O(1) | | `Arena.len` | [marks](/docs/ref/std/marks) | O(1) | | `Arena.new` | [marks](/docs/ref/std/marks) | O(cap) | | `Arena.reserve` | [marks](/docs/ref/std/marks) | O(cap) | | `Arena.set` | [marks](/docs/ref/std/marks) | O(1) | | `ArithDiff` | [prefix](/docs/ref/std/prefix) | | | `ArithDiff.add` | [prefix](/docs/ref/std/prefix) | O(1) | | `ArithDiff.add_arith` | [prefix](/docs/ref/std/prefix) | O(1) | | `ArithDiff.finish` | [prefix](/docs/ref/std/prefix) | O(\|D\|) time and space | | `ArithDiff.new` | [prefix](/docs/ref/std/prefix) | O(\|D\|) time and space | | `AssignAction` | [algebra](/docs/ref/std/algebra) | | | `AugSortedBag` | [bag](/docs/ref/std/bag) | | | `AugSortedBag.add` | [bag](/docs/ref/std/bag) | O(log n) expected | | `AugSortedBag.all` | [bag](/docs/ref/std/bag) | O(1) | | `AugSortedBag.count` | [bag](/docs/ref/std/bag) | O(log n) expected | | `AugSortedBag.drop_min` | [bag](/docs/ref/std/bag) | | | `AugSortedBag.each` | [bag](/docs/ref/std/bag) | O(1) amortized per step | | `AugSortedBag.extreme` | [bag](/docs/ref/std/bag) | | | `AugSortedBag.first` | [bag](/docs/ref/std/bag) | O(1) | | `AugSortedBag.fold_between` | [bag](/docs/ref/std/bag) | O(log n) expected | | `AugSortedBag.fold_from` | [bag](/docs/ref/std/bag) | | | `AugSortedBag.fold_ge` | [bag](/docs/ref/std/bag) | O(log n) expected | | `AugSortedBag.fold_gt` | [bag](/docs/ref/std/bag) | O(log n) expected | | `AugSortedBag.fold_le` | [bag](/docs/ref/std/bag) | O(log n) expected | | `AugSortedBag.fold_lt` | [bag](/docs/ref/std/bag) | O(log n) expected | | `AugSortedBag.fold_upto` | [bag](/docs/ref/std/bag) | | | `AugSortedBag.is_empty` | [bag](/docs/ref/std/bag) | O(1) | | `AugSortedBag.last` | [bag](/docs/ref/std/bag) | O(1) | | `AugSortedBag.len` | [bag](/docs/ref/std/bag) | O(1) | | `AugSortedBag.merge` | [bag](/docs/ref/std/bag) | | | `AugSortedBag.new` | [bag](/docs/ref/std/bag) | O(1) | | `AugSortedBag.nth` | [bag](/docs/ref/std/bag) | O(log n) expected | | `AugSortedBag.pull` | [bag](/docs/ref/std/bag) | | | `AugSortedBag.rank` | [bag](/docs/ref/std/bag) | O(log n) expected | | `AugSortedBag.rank_le` | [bag](/docs/ref/std/bag) | | | `AugSortedBag.remove` | [bag](/docs/ref/std/bag) | O(log n) expected | | `AugSortedBag.reserve` | [bag](/docs/ref/std/bag) | O(cap) when the pool grows, O(1) otherwise | | `AugSortedBag.size` | [bag](/docs/ref/std/bag) | | | `AugSortedBag.split` | [bag](/docs/ref/std/bag) | | | `AugSortedBag.sub` | [bag](/docs/ref/std/bag) | | | `AugSortedSet` | [bag](/docs/ref/std/bag) | | | `AugSortedSet.add` | [bag](/docs/ref/std/bag) | O(log n) expected | | `AugSortedSet.all` | [bag](/docs/ref/std/bag) | O(1) | | `AugSortedSet.contains` | [bag](/docs/ref/std/bag) | O(log n) expected | | `AugSortedSet.each` | [bag](/docs/ref/std/bag) | O(1) amortized per step | | `AugSortedSet.first` | [bag](/docs/ref/std/bag) | O(1) | | `AugSortedSet.fold_between` | [bag](/docs/ref/std/bag) | O(log n) expected | | `AugSortedSet.fold_ge` | [bag](/docs/ref/std/bag) | O(log n) expected | | `AugSortedSet.fold_gt` | [bag](/docs/ref/std/bag) | O(log n) expected | | `AugSortedSet.fold_le` | [bag](/docs/ref/std/bag) | O(log n) expected | | `AugSortedSet.fold_lt` | [bag](/docs/ref/std/bag) | O(log n) expected | | `AugSortedSet.is_empty` | [bag](/docs/ref/std/bag) | O(1) | | `AugSortedSet.last` | [bag](/docs/ref/std/bag) | O(1) | | `AugSortedSet.len` | [bag](/docs/ref/std/bag) | O(1) | | `AugSortedSet.new` | [bag](/docs/ref/std/bag) | O(1) | | `AugSortedSet.nth` | [bag](/docs/ref/std/bag) | O(log n) expected | | `AugSortedSet.rank` | [bag](/docs/ref/std/bag) | O(log n) expected | | `AugSortedSet.remove` | [bag](/docs/ref/std/bag) | O(log n) expected | | `AugSortedSet.reserve` | [bag](/docs/ref/std/bag) | O(cap) when the pool grows, O(1) otherwise | | `BagCursor` | [bag](/docs/ref/std/bag) | | | `Barrett` | [mod](/docs/ref/std/mod) | | | `Barrett.mul` | [mod](/docs/ref/std/mod) | O(1) | | `Barrett.new` | [mod](/docs/ref/std/mod) | O(1) | | `Barrett.reduce` | [mod](/docs/ref/std/mod) | O(1) | | `BeatsSegTree` | [beats](/docs/ref/std/beats) | | | `BeatsSegTree.add` | [beats](/docs/ref/std/beats) | O(log \|D\|) | | `BeatsSegTree.add_rec` | [beats](/docs/ref/std/beats) | | | `BeatsSegTree.all_max` | [beats](/docs/ref/std/beats) | O(1) | | `BeatsSegTree.all_min` | [beats](/docs/ref/std/beats) | O(1) | | `BeatsSegTree.all_sum` | [beats](/docs/ref/std/beats) | O(1) | | `BeatsSegTree.apply_add` | [beats](/docs/ref/std/beats) | | | `BeatsSegTree.apply_chmax` | [beats](/docs/ref/std/beats) | | | `BeatsSegTree.apply_chmin` | [beats](/docs/ref/std/beats) | | | `BeatsSegTree.assign` | [beats](/docs/ref/std/beats) | O(log \|D\|) amortized | | `BeatsSegTree.build` | [beats](/docs/ref/std/beats) | | | `BeatsSegTree.chdiv` | [beats](/docs/ref/std/beats) | O(log \|D\| log V) amortized | | `BeatsSegTree.chmax` | [beats](/docs/ref/std/beats) | O(log \|D\|) amortized; O(log^2 \|D\|) amortized when mixed with `add` | | `BeatsSegTree.chmax_rec` | [beats](/docs/ref/std/beats) | | | `BeatsSegTree.chmin` | [beats](/docs/ref/std/beats) | O(log \|D\|) amortized; O(log^2 \|D\|) amortized when mixed with `add` | | `BeatsSegTree.chmin_rec` | [beats](/docs/ref/std/beats) | | | `BeatsSegTree.chmod` | [beats](/docs/ref/std/beats) | O(log \|D\| log V) amortized | | `BeatsSegTree.div_rec` | [beats](/docs/ref/std/beats) | | | `BeatsSegTree.get` | [beats](/docs/ref/std/beats) | O(log \|D\|) | | `BeatsSegTree.max_rec` | [beats](/docs/ref/std/beats) | | | `BeatsSegTree.max_val` | [beats](/docs/ref/std/beats) | O(log \|D\|) | | `BeatsSegTree.min_rec` | [beats](/docs/ref/std/beats) | | | `BeatsSegTree.min_val` | [beats](/docs/ref/std/beats) | O(log \|D\|) | | `BeatsSegTree.new` | [beats](/docs/ref/std/beats) | O(\|D\|) | | `BeatsSegTree.pull` | [beats](/docs/ref/std/beats) | | | `BeatsSegTree.push` | [beats](/docs/ref/std/beats) | | | `BeatsSegTree.set` | [beats](/docs/ref/std/beats) | O(log \|D\|) | | `BeatsSegTree.sum` | [beats](/docs/ref/std/beats) | O(log \|D\|) | | `BeatsSegTree.sum_rec` | [beats](/docs/ref/std/beats) | | | `BigInt` | [math](/docs/ref/std/math) | | | `BigInt.abs` | [math](/docs/ref/std/math) | O(n) | | `BigInt.add` | [math](/docs/ref/std/math) | | | `BigInt.div` | [math](/docs/ref/std/math) | | | `BigInt.divmod` | [math](/docs/ref/std/math) | O(n * m) | | `BigInt.from_int` | [math](/docs/ref/std/math) | O(1) | | `BigInt.from_str` | [math](/docs/ref/std/math) | O(s.len) | | `BigInt.gcd` | [math](/docs/ref/std/math) | O(n^2) | | `BigInt.lt` | [math](/docs/ref/std/math) | | | `BigInt.mul` | [math](/docs/ref/std/math) | | | `BigInt.neg` | [math](/docs/ref/std/math) | | | `BigInt.show` | [math](/docs/ref/std/math) | | | `BigInt.sub` | [math](/docs/ref/std/math) | | | `BigInt.to_str` | [math](/docs/ref/std/math) | O(n) | | `BitMat` | [matrix](/docs/ref/std/matrix) | | | `BitMat.det` | [matrix](/docs/ref/std/matrix) | O(n^3 / 64) | | `BitMat.get` | [matrix](/docs/ref/std/matrix) | O(1) | | `BitMat.identity` | [matrix](/docs/ref/std/matrix) | O(n^2 / 64) time and space | | `BitMat.inverse` | [matrix](/docs/ref/std/matrix) | O(n^3 / 64) | | `BitMat.mul` | [matrix](/docs/ref/std/matrix) | O(rows * cols * o.cols / 64) | | `BitMat.new` | [matrix](/docs/ref/std/matrix) | O(rows * cols / 64) time and space | | `BitMat.rank` | [matrix](/docs/ref/std/matrix) | O(rows * cols * min(rows, cols) / 64) | | `BitMat.set` | [matrix](/docs/ref/std/matrix) | O(1) | | `BitMat.solve` | [matrix](/docs/ref/std/matrix) | O(rows * cols * min(rows, cols) / 64) | | `BitMat.solve_space` | [matrix](/docs/ref/std/matrix) | O(rows * cols * min(rows, cols) / 64) | | `Bitset` | [bitset](/docs/ref/std/bitset) | | | `Bitset.add` | [bitset](/docs/ref/std/bitset) | O(1) | | `Bitset.any` | [bitset](/docs/ref/std/bitset) | O(K / 64 + visited) words scanned and calls of `pred` | | `Bitset.bitand` | [bitset](/docs/ref/std/bitset) | O(K / 64) time and space | | `Bitset.bitor` | [bitset](/docs/ref/std/bitset) | O(K / 64) time and space | | `Bitset.bitxor` | [bitset](/docs/ref/std/bitset) | O(K / 64) time and space | | `Bitset.clear` | [bitset](/docs/ref/std/bitset) | O(K / 64) | | `Bitset.complement` | [bitset](/docs/ref/std/bitset) | O(K / 64) time and space | | `Bitset.contains` | [bitset](/docs/ref/std/bitset) | O(1) | | `Bitset.count` | [bitset](/docs/ref/std/bitset) | O(1) | | `Bitset.count_below` | [bitset](/docs/ref/std/bitset) | O(K / 64) | | `Bitset.count_range` | [bitset](/docs/ref/std/bitset) | O(r.len / 64 + 1) | | `Bitset.each` | [bitset](/docs/ref/std/bitset) | O(K / 64 + len) to walk, O(1) per member amortized | | `Bitset.each_rev` | [bitset](/docs/ref/std/bitset) | O(K / 64 + len) to walk | | `Bitset.empty` | [bitset](/docs/ref/std/bitset) | O(K / 64) time and space | | `Bitset.find` | [bitset](/docs/ref/std/bitset) | O(K / 64 + visited) | | `Bitset.first` | [bitset](/docs/ref/std/bitset) | O(K / 64) | | `Bitset.flip_range` | [bitset](/docs/ref/std/bitset) | O(r.len / 64 + 1) | | `Bitset.from` | [bitset](/docs/ref/std/bitset) | O(K) time, O(K / 64) space | | `Bitset.full` | [bitset](/docs/ref/std/bitset) | O(K / 64) time and space | | `Bitset.intersect` | [bitset](/docs/ref/std/bitset) | O(K / 64) | | `Bitset.is_empty` | [bitset](/docs/ref/std/bitset) | O(1) | | `Bitset.len` | [bitset](/docs/ref/std/bitset) | O(1) | | `Bitset.meets` | [bitset](/docs/ref/std/bitset) | O(K / 64), less on an early hit | | `Bitset.new` | [bitset](/docs/ref/std/bitset) | O(K / 64) time and space | | `Bitset.next` | [bitset](/docs/ref/std/bitset) | O(K / 64) | | `Bitset.nth` | [bitset](/docs/ref/std/bitset) | O(K / 64) | | `Bitset.of` | [bitset](/docs/ref/std/bitset) | O(K / 64 + xs.len) time, O(K / 64) space | | `Bitset.prev` | [bitset](/docs/ref/std/bitset) | O(K / 64) | | `Bitset.recount` | [bitset](/docs/ref/std/bitset) | | | `Bitset.remove` | [bitset](/docs/ref/std/bitset) | O(1) | | `Bitset.rfind` | [bitset](/docs/ref/std/bitset) | O(K / 64 + visited) | | `Bitset.set` | [bitset](/docs/ref/std/bitset) | O(K / 64) time and space | | `Bitset.set_range` | [bitset](/docs/ref/std/bitset) | O(r.len / 64 + 1) | | `Bitset.shift_down` | [bitset](/docs/ref/std/bitset) | O(K / 64) | | `Bitset.shift_or` | [bitset](/docs/ref/std/bitset) | O(K / 64) | | `Bitset.shift_up` | [bitset](/docs/ref/std/bitset) | O(K / 64) | | `Bitset.shifted` | [bitset](/docs/ref/std/bitset) | O(K / 64) time and space, for any `k` | | `Bitset.single` | [bitset](/docs/ref/std/bitset) | O(K / 64) time and space | | `Bitset.subset_sums` | [bitset](/docs/ref/std/bitset) | O(K sqrt(S) / 64) time, where S is the sum of `weights`; O(K / 64) space | | `Bitset.subtract` | [bitset](/docs/ref/std/bitset) | O(K / 64) | | `Bitset.symmetric` | [bitset](/docs/ref/std/bitset) | O(K / 64) | | `Bitset.toggle` | [bitset](/docs/ref/std/bitset) | O(1) | | `Bitset.trim` | [bitset](/docs/ref/std/bitset) | | | `Bitset.union` | [bitset](/docs/ref/std/bitset) | O(K / 64) | | `Bitset.with` | [bitset](/docs/ref/std/bitset) | O(K / 64) time and space | | `Bitset.without` | [bitset](/docs/ref/std/bitset) | O(K / 64) time and space | | `Bitset.show` | [bitset](/docs/ref/std/bitset) | | | `Bitset.sub` | [bitset](/docs/ref/std/bitset) | | | `BucketCount` | [bag](/docs/ref/std/bag) | | | `BucketCount.add` | [bag](/docs/ref/std/bag) | O(1) | | `BucketCount.clear` | [bag](/docs/ref/std/bag) | O(r.len) | | `BucketCount.count` | [bag](/docs/ref/std/bag) | O(1) | | `BucketCount.count_lt` | [bag](/docs/ref/std/bag) | O(sqrt(N)) | | `BucketCount.is_empty` | [bag](/docs/ref/std/bag) | O(1) | | `BucketCount.kth` | [bag](/docs/ref/std/bag) | O(sqrt(N)) | | `BucketCount.len` | [bag](/docs/ref/std/bag) | O(1) | | `BucketCount.new` | [bag](/docs/ref/std/bag) | O(r.len) | | `BucketCount.remove` | [bag](/docs/ref/std/bag) | O(1) | | `ByAngle` | [geometry](/docs/ref/std/geometry) | | | `ByAngle.lt` | [geometry](/docs/ref/std/geometry) | | | `ByAngleFrom` | [geometry](/docs/ref/std/geometry) | | | `ByAngleFrom.lt` | [geometry](/docs/ref/std/geometry) | | | `Centroids` | [tree](/docs/ref/std/tree) | | | `Centroids.ancestors` | [tree](/docs/ref/std/tree) | O(1) per entry, O(log n) in all | | `Centroids.depth` | [tree](/docs/ref/std/tree) | O(1) | | `Centroids.new` | [tree](/docs/ref/std/tree) | O(n log n) time and memory | | `Centroids.parent` | [tree](/docs/ref/std/tree) | O(1) | | `Centroids.piece` | [tree](/docs/ref/std/tree) | O(size of the piece) | | `Circle` | [geometry](/docs/ref/std/geometry) | | | `Circle.area` | [geometry](/docs/ref/std/geometry) | O(1) | | `Circle.circumference` | [geometry](/docs/ref/std/geometry) | O(1) | | `Circle.locate` | [geometry](/docs/ref/std/geometry) | O(1) | | `Circle.through` | [geometry](/docs/ref/std/geometry) | O(1) | | `ColorMatroid` | [flow](/docs/ref/std/flow) | | | `ColorMatroid.new` | [flow](/docs/ref/std/flow) | O(1); each `rebuild` is O(E) | | `Comb` | [mod](/docs/ref/std/mod) | | | `Comb.arrange` | [mod](/docs/ref/std/mod) | O(1) amortized | | `Comb.catalan` | [mod](/docs/ref/std/mod) | O(1) amortized | | `Comb.choose` | [mod](/docs/ref/std/mod) | O(1) amortized for `n < M.MOD`; O(log_P n) otherwise | | `Comb.choose_lucas` | [mod](/docs/ref/std/mod) | | | `Comb.derange` | [mod](/docs/ref/std/mod) | O(1) amortized, O(n) table | | `Comb.ensure` | [mod](/docs/ref/std/mod) | | | `Comb.fact` | [mod](/docs/ref/std/mod) | O(1) amortized | | `Comb.grow` | [mod](/docs/ref/std/mod) | | | `Comb.inv` | [mod](/docs/ref/std/mod) | O(1) amortized | | `Comb.inv_fact` | [mod](/docs/ref/std/mod) | O(1) amortized | | `Comb.multichoose` | [mod](/docs/ref/std/mod) | O(1) amortized | | `Comb.multinomial` | [mod](/docs/ref/std/mod) | O(ks.len) amortized | | `Comb.new` | [mod](/docs/ref/std/mod) | O(min(limit, P)) | | `Commutative` | [algebra](/docs/ref/std/algebra) | | | `Complement` | [graph](/docs/ref/std/graph) | | | `Complement.out` | [graph](/docs/ref/std/graph) | O(\|V\| + deg u) | | `Compressed` | [seq](/docs/ref/std/seq) | | | `Compressed.at` | [seq](/docs/ref/std/seq) | O(log n) | | `Compressed.contains` | [seq](/docs/ref/std/seq) | O(log n) | | `Compressed.first_ge` | [seq](/docs/ref/std/seq) | O(log n) | | `Compressed.first_gt` | [seq](/docs/ref/std/seq) | O(log n) | | `Compressed.get` | [seq](/docs/ref/std/seq) | O(1) | | `Compressed.last_le` | [seq](/docs/ref/std/seq) | O(log n) | | `Compressed.last_lt` | [seq](/docs/ref/std/seq) | O(log n) | | `Compressed.len` | [seq](/docs/ref/std/seq) | O(1) | | `Compressed.slice` | [seq](/docs/ref/std/seq) | O(r.len) | | `Compressed.try_at` | [seq](/docs/ref/std/seq) | O(log n) | | `Concave` | [slope](/docs/ref/std/slope) | | | `Concave.add_abs` | [slope](/docs/ref/std/slope) | O(log n) expected | | `Concave.add_const` | [slope](/docs/ref/std/slope) | O(1) | | `Concave.add_left` | [slope](/docs/ref/std/slope) | O(log n) expected | | `Concave.add_linear` | [slope](/docs/ref/std/slope) | O(1) | | `Concave.add_quadratic` | [slope](/docs/ref/std/slope) | O(1) | | `Concave.add_right` | [slope](/docs/ref/std/slope) | O(log n) expected | | `Concave.argmax` | [slope](/docs/ref/std/slope) | O(log n) expected (O(n) in the current implementation) | | `Concave.at` | [slope](/docs/ref/std/slope) | O(log n) expected (O(c - lo + log n) in the current implementation) | | `Concave.count_at_least` | [slope](/docs/ref/std/slope) | | | `Concave.flat` | [slope](/docs/ref/std/slope) | O(\|r\| log \|r\|) expected | | `Concave.hi` | [slope](/docs/ref/std/slope) | O(1) | | `Concave.lo` | [slope](/docs/ref/std/slope) | O(1) | | `Concave.max` | [slope](/docs/ref/std/slope) | O(log n) expected (O(n) in the current implementation) | | `Concave.max_convolve` | [slope](/docs/ref/std/slope) | O(\|g\| log n) expected, for `\|g\|` slopes in `g` | | `Concave.point` | [slope](/docs/ref/std/slope) | O(1) | | `Concave.prefix_max` | [slope](/docs/ref/std/slope) | O(log n) expected (O(n log n) in the current implementation) | | `Concave.reserve` | [slope](/docs/ref/std/slope) | O(n) | | `Concave.shift` | [slope](/docs/ref/std/slope) | O(1) | | `Concave.slide_max` | [slope](/docs/ref/std/slope) | O(b - a + log n) expected | | `Concave.suffix_max` | [slope](/docs/ref/std/slope) | O(log n) expected (O(n log n) in the current implementation) | | `Convex` | [slope](/docs/ref/std/slope) | | | `Convex.add_abs` | [slope](/docs/ref/std/slope) | O(log n) expected | | `Convex.add_const` | [slope](/docs/ref/std/slope) | O(1) | | `Convex.add_left` | [slope](/docs/ref/std/slope) | O(log n) expected | | `Convex.add_linear` | [slope](/docs/ref/std/slope) | O(1) | | `Convex.add_quadratic` | [slope](/docs/ref/std/slope) | O(1) | | `Convex.add_right` | [slope](/docs/ref/std/slope) | O(log n) expected | | `Convex.argmin` | [slope](/docs/ref/std/slope) | O(log n) expected (O(n) in the current implementation) | | `Convex.at` | [slope](/docs/ref/std/slope) | O(log n) expected (O(c - lo + log n) in the current implementation) | | `Convex.flat` | [slope](/docs/ref/std/slope) | O(\|r\| log \|r\|) expected | | `Convex.hi` | [slope](/docs/ref/std/slope) | O(1) | | `Convex.lo` | [slope](/docs/ref/std/slope) | O(1) | | `Convex.min` | [slope](/docs/ref/std/slope) | O(log n) expected (O(n) in the current implementation) | | `Convex.min_convolve` | [slope](/docs/ref/std/slope) | O(\|g\| log n) expected, for `\|g\|` slopes in `g` | | `Convex.point` | [slope](/docs/ref/std/slope) | O(1) | | `Convex.prefix_min` | [slope](/docs/ref/std/slope) | O(log n) expected (O(n log n) in the current implementation) | | `Convex.shift` | [slope](/docs/ref/std/slope) | O(1) | | `Convex.slide_min` | [slope](/docs/ref/std/slope) | O(b - a + log n) expected | | `Convex.suffix_min` | [slope](/docs/ref/std/slope) | O(log n) expected (O(n log n) in the current implementation) | | `CostFlow` | [flow](/docs/ref/std/flow) | | | `CostFlow.add` | [flow](/docs/ref/std/flow) | O(1) amortized; two arcs of memory | | `CostFlow.arcs` | [flow](/docs/ref/std/flow) | O(E) for the whole walk | | `CostFlow.cancel_cycles` | [flow](/docs/ref/std/flow) | O(V E log V) worst case, by cost scaling | | `CostFlow.cap` | [flow](/docs/ref/std/flow) | O(1) | | `CostFlow.cost` | [flow](/docs/ref/std/flow) | O(1) | | `CostFlow.flow` | [flow](/docs/ref/std/flow) | O(1) | | `CostFlow.min_cost_flow` | [flow](/docs/ref/std/flow) | O(F E log V) for F augmenting paths, plus O(V E) once when a residual arc has a negative cost | | `CostFlow.new` | [flow](/docs/ref/std/flow) | O(n) for n = `V.count` | | `CostFlow.potentials` | [flow](/docs/ref/std/flow) | | | `CostFlow.set_cap` | [flow](/docs/ref/std/flow) | O(1) | | `CostFlow.slope` | [flow](/docs/ref/std/flow) | as `min_cost_flow` | | `CostFlow.source` | [flow](/docs/ref/std/flow) | O(1) | | `CostFlow.target` | [flow](/docs/ref/std/flow) | O(1) | | `Counter` | [hashmap](/docs/ref/std/hashmap) | | | `Counter.absorb` | [hashmap](/docs/ref/std/hashmap) | O(min(\|self\|, \|other\|)) expected | | `Counter.add` | [hashmap](/docs/ref/std/hashmap) | O(1) expected amortized | | `Counter.clear` | [hashmap](/docs/ref/std/hashmap) | O(n) | | `Counter.contains` | [hashmap](/docs/ref/std/hashmap) | O(1) expected | | `Counter.get` | [hashmap](/docs/ref/std/hashmap) | O(1) expected | | `Counter.is_empty` | [hashmap](/docs/ref/std/hashmap) | O(1) | | `Counter.items` | [hashmap](/docs/ref/std/hashmap) | O(1) to make, O(1) per step | | `Counter.keys` | [hashmap](/docs/ref/std/hashmap) | O(1) to make, O(1) per step | | `Counter.len` | [hashmap](/docs/ref/std/hashmap) | O(1) | | `Counter.most_common` | [hashmap](/docs/ref/std/hashmap) | O(n log n) | | `Counter.new` | [hashmap](/docs/ref/std/hashmap) | O(1) | | `Counter.of` | [hashmap](/docs/ref/std/hashmap) | O(n) expected | | `Counter.remove` | [hashmap](/docs/ref/std/hashmap) | O(1) expected | | `Counter.reserve` | [hashmap](/docs/ref/std/hashmap) | O(cap) when the table grows, O(1) otherwise | | `Counter.set` | [hashmap](/docs/ref/std/hashmap) | O(1) expected amortized | | `Counter.take` | [hashmap](/docs/ref/std/hashmap) | O(1) | | `Counter.total` | [hashmap](/docs/ref/std/hashmap) | O(n) | | `Counter.values` | [hashmap](/docs/ref/std/hashmap) | O(1) to make, O(1) per step | | `Counter.pop` | [window](/docs/ref/std/window) | | | `Counter.push` | [window](/docs/ref/std/window) | | | `Curved` | [ntt](/docs/ref/std/ntt) | | | `Deque` | [deque](/docs/ref/std/deque) | | | `Deque.clear` | [deque](/docs/ref/std/deque) | O(1) | | `Deque.each` | [deque](/docs/ref/std/deque) | O(1) per step | | `Deque.each_rev` | [deque](/docs/ref/std/deque) | O(1) per step | | `Deque.first` | [deque](/docs/ref/std/deque) | O(1) | | `Deque.get` | [deque](/docs/ref/std/deque) | O(1) | | `Deque.grow_to` | [deque](/docs/ref/std/deque) | | | `Deque.is_empty` | [deque](/docs/ref/std/deque) | O(1) | | `Deque.items` | [deque](/docs/ref/std/deque) | O(1) to make, O(1) per step | | `Deque.last` | [deque](/docs/ref/std/deque) | O(1) | | `Deque.len` | [deque](/docs/ref/std/deque) | O(1) | | `Deque.new` | [deque](/docs/ref/std/deque) | O(1); nothing is allocated until the first push | | `Deque.of` | [deque](/docs/ref/std/deque) | O(n) | | `Deque.pop` | [deque](/docs/ref/std/deque) | O(1) | | `Deque.pop_front` | [deque](/docs/ref/std/deque) | O(1) | | `Deque.pop_front_while` | [deque](/docs/ref/std/deque) | O(k) for `k` removed | | `Deque.pop_while` | [deque](/docs/ref/std/deque) | O(k) for `k` removed | | `Deque.push` | [deque](/docs/ref/std/deque) | O(1) amortized; a full ring doubles | | `Deque.push_front` | [deque](/docs/ref/std/deque) | O(1) amortized; a full ring doubles | | `Deque.reserve` | [deque](/docs/ref/std/deque) | O(1) when empty, O(cap) otherwise | | `Deque.rotate_left` | [deque](/docs/ref/std/deque) | O(min(k, n - k)) after reducing `k` mod `n` | | `Deque.rotate_right` | [deque](/docs/ref/std/deque) | O(min(k, n - k)) after reducing `k` mod `n` | | `Deque.set` | [deque](/docs/ref/std/deque) | O(1) | | `Deque.take` | [deque](/docs/ref/std/deque) | O(1) | | `Deque.to_list` | [deque](/docs/ref/std/deque) | O(n), one new `List` | | `Desc` | [algebra](/docs/ref/std/algebra) | | | `Desc.lt` | [algebra](/docs/ref/std/algebra) | | | `Desc.show` | [algebra](/docs/ref/std/algebra) | | | `Diff` | [prefix](/docs/ref/std/prefix) | | | `Diff.add` | [prefix](/docs/ref/std/prefix) | O(1) | | `Diff.finish` | [prefix](/docs/ref/std/prefix) | O(\|D\|) time and space | | `Diff.new` | [prefix](/docs/ref/std/prefix) | O(\|D\|) time and space | | `Dir4` | [grid](/docs/ref/std/grid) | | | `Dir4.all` | [grid](/docs/ref/std/grid) | O(1) | | `Dir4.back` | [grid](/docs/ref/std/grid) | O(1) | | `Dir4.ccw` | [grid](/docs/ref/std/grid) | O(1) | | `Dir4.cw` | [grid](/docs/ref/std/grid) | O(1) | | `Dir4.delta` | [grid](/docs/ref/std/grid) | O(1) | | `Dir4.down` | [grid](/docs/ref/std/grid) | O(1) | | `Dir4.from` | [grid](/docs/ref/std/grid) | O(1) | | `Dir4.left` | [grid](/docs/ref/std/grid) | O(1) | | `Dir4.right` | [grid](/docs/ref/std/grid) | O(1) | | `Dir4.up` | [grid](/docs/ref/std/grid) | O(1) | | `Dir8` | [grid](/docs/ref/std/grid) | | | `Dir8.all` | [grid](/docs/ref/std/grid) | O(1) | | `Dir8.back` | [grid](/docs/ref/std/grid) | O(1) | | `Dir8.ccw` | [grid](/docs/ref/std/grid) | O(1) | | `Dir8.cw` | [grid](/docs/ref/std/grid) | O(1) | | `Dir8.delta` | [grid](/docs/ref/std/grid) | O(1) | | `Dir8.from` | [grid](/docs/ref/std/grid) | O(1) | | `DirichletSum` | [math](/docs/ref/std/math) | | | `DirichletSum.new` | [math](/docs/ref/std/math) | O(f_small.len) to build; queries as `sum` | | `DirichletSum.sum` | [math](/docs/ref/std/math) | O(1) cached; O(n^(2/3)) total across all `n / i` queries | | `Disjoint` | [ntt](/docs/ref/std/ntt) | | | `DisjointSparseTable` | [sparse](/docs/ref/std/sparse) | | | `DisjointSparseTable.all` | [sparse](/docs/ref/std/sparse) | O(1) | | `DisjointSparseTable.fold` | [sparse](/docs/ref/std/sparse) | O(1), at most one `op` call | | `DisjointSparseTable.get` | [sparse](/docs/ref/std/sparse) | O(1) | | `DisjointSparseTable.new` | [sparse](/docs/ref/std/sparse) | O(\|D\| log \|D\|) time and memory, `op` called O(\|D\| log \|D\|) times | | `DisjointSparseTable.try_fold` | [sparse](/docs/ref/std/sparse) | O(1) | | `Dsu` | [dsu](/docs/ref/std/dsu) | | | `Dsu.components` | [dsu](/docs/ref/std/dsu) | O(1) | | `Dsu.find` | [dsu](/docs/ref/std/dsu) | O(alpha(n)) amortized; O(log n) after the first `mark` | | `Dsu.find_ord` | [dsu](/docs/ref/std/dsu) | | | `Dsu.groups` | [dsu](/docs/ref/std/dsu) | O(n alpha(n)); allocates the lists | | `Dsu.mark` | [dsu](/docs/ref/std/dsu) | O(1) | | `Dsu.merge` | [dsu](/docs/ref/std/dsu) | as `unite` | | `Dsu.new` | [dsu](/docs/ref/std/dsu) | O(n) for n = `V.count`; one `[V]` array | | `Dsu.roots` | [dsu](/docs/ref/std/dsu) | O(n) for the whole walk, no allocation | | `Dsu.same` | [dsu](/docs/ref/std/dsu) | O(alpha(n)) amortized; O(log n) after the first `mark` | | `Dsu.size` | [dsu](/docs/ref/std/dsu) | O(alpha(n)) amortized; O(log n) after the first `mark` | | `Dsu.undo_to` | [dsu](/docs/ref/std/dsu) | O(1) per undone `unite` | | `Dsu.unite` | [dsu](/docs/ref/std/dsu) | O(alpha(n)) amortized; O(log n) after the first `mark`, plus one log entry | | `Dsu.mark` | [window](/docs/ref/std/window) | | | `Dsu.undo_to` | [window](/docs/ref/std/window) | | | `DsuOf` | [dsu](/docs/ref/std/dsu) | | | `DsuOf.components` | [dsu](/docs/ref/std/dsu) | O(1) | | `DsuOf.find` | [dsu](/docs/ref/std/dsu) | O(alpha(n)) amortized; O(log n) after the first `mark` | | `DsuOf.get` | [dsu](/docs/ref/std/dsu) | O(alpha(n)) amortized; O(log n) after the first `mark` | | `DsuOf.groups` | [dsu](/docs/ref/std/dsu) | O(n alpha(n)); allocates the lists | | `DsuOf.mark` | [dsu](/docs/ref/std/dsu) | O(1) | | `DsuOf.merge` | [dsu](/docs/ref/std/dsu) | as `unite` | | `DsuOf.new` | [dsu](/docs/ref/std/dsu) | O(n) calls of `init`; three `[V]` arrays | | `DsuOf.roots` | [dsu](/docs/ref/std/dsu) | O(n) for the whole walk, no allocation | | `DsuOf.same` | [dsu](/docs/ref/std/dsu) | O(alpha(n)) amortized; O(log n) after the first `mark` | | `DsuOf.set` | [dsu](/docs/ref/std/dsu) | O(alpha(n)) amortized; O(log n) after the first `mark`, plus one log entry | | `DsuOf.size` | [dsu](/docs/ref/std/dsu) | O(alpha(n)) amortized; O(log n) after the first `mark` | | `DsuOf.undo_to` | [dsu](/docs/ref/std/dsu) | O(1) per undone change | | `DsuOf.unite` | [dsu](/docs/ref/std/dsu) | as [`Dsu.unite`](Dsu.unite), plus one call of `join` | | `DsuOf.values` | [dsu](/docs/ref/std/dsu) | O(n) for the whole walk, no allocation | | `DsuOf.mark` | [window](/docs/ref/std/window) | | | `DsuOf.undo_to` | [window](/docs/ref/std/window) | | | `DualFenwick` | [fenwick](/docs/ref/std/fenwick) | | | `DualFenwick.add` | [fenwick](/docs/ref/std/fenwick) | O(log \|D\|) | | `DualFenwick.add_at` | [fenwick](/docs/ref/std/fenwick) | | | `DualFenwick.clear` | [fenwick](/docs/ref/std/fenwick) | O(\|D\|) | | `DualFenwick.get` | [fenwick](/docs/ref/std/fenwick) | O(log \|D\|) | | `DualFenwick.new` | [fenwick](/docs/ref/std/fenwick) | O(\|D\|) time; memory \|D\| + 1 values | | `DynamicAhoCorasick` | [strings](/docs/ref/std/strings) | | | `DynamicAhoCorasick.add` | [strings](/docs/ref/std/strings) | O(\|pattern\| * \|A\| * log n) amortized | | `DynamicAhoCorasick.count_matches` | [strings](/docs/ref/std/strings) | O(\|text\| * log n) | | `DynamicAhoCorasick.is_empty` | [strings](/docs/ref/std/strings) | O(1) | | `DynamicAhoCorasick.len` | [strings](/docs/ref/std/strings) | O(1) | | `DynamicAhoCorasick.new` | [strings](/docs/ref/std/strings) | O(1) | | `DynamicAhoCorasick.remove` | [strings](/docs/ref/std/strings) | O(\|pattern\| * \|A\| * log n) amortized | | `DynamicHash` | [strings](/docs/ref/std/strings) | | | `DynamicHash.all` | [strings](/docs/ref/std/strings) | O(1) | | `DynamicHash.get` | [strings](/docs/ref/std/strings) | O(log n) | | `DynamicHash.is_empty` | [strings](/docs/ref/std/strings) | O(1) | | `DynamicHash.is_palindrome` | [strings](/docs/ref/std/strings) | O(log n) | | `DynamicHash.len` | [strings](/docs/ref/std/strings) | O(1) | | `DynamicHash.new` | [strings](/docs/ref/std/strings) | O(n) | | `DynamicHash.rev_get` | [strings](/docs/ref/std/strings) | O(log n) | | `DynamicHash.set` | [strings](/docs/ref/std/strings) | O(log n) | | `DynamicOrderTree` | [segtree](/docs/ref/std/segtree) | | | `DynamicOrderTree.below` | [segtree](/docs/ref/std/segtree) | | | `DynamicOrderTree.bump` | [segtree](/docs/ref/std/segtree) | | | `DynamicOrderTree.count_in` | [segtree](/docs/ref/std/segtree) | O(log^2 \|D\|) | | `DynamicOrderTree.count_lt` | [segtree](/docs/ref/std/segtree) | O(log^2 \|D\|) | | `DynamicOrderTree.get` | [segtree](/docs/ref/std/segtree) | O(1) | | `DynamicOrderTree.kth` | [segtree](/docs/ref/std/segtree) | O(log^2 \|D\|) | | `DynamicOrderTree.new` | [segtree](/docs/ref/std/segtree) | O(\|D\| log^2 \|D\|) time and memory | | `DynamicOrderTree.set` | [segtree](/docs/ref/std/segtree) | O(log^2 \|D\|) | | `DynamicOrderTree.span_count` | [segtree](/docs/ref/std/segtree) | | | `DynBitset` | [bitset](/docs/ref/std/bitset) | | | `DynBitset.add` | [bitset](/docs/ref/std/bitset) | O(1) | | `DynBitset.cap` | [bitset](/docs/ref/std/bitset) | O(1) | | `DynBitset.clear` | [bitset](/docs/ref/std/bitset) | O(cap / 64) | | `DynBitset.contains` | [bitset](/docs/ref/std/bitset) | O(1) | | `DynBitset.count_below` | [bitset](/docs/ref/std/bitset) | O(cap / 64) | | `DynBitset.count_range` | [bitset](/docs/ref/std/bitset) | O(r.len / 64 + 1) | | `DynBitset.each` | [bitset](/docs/ref/std/bitset) | O(cap / 64 + len) to walk | | `DynBitset.each_rev` | [bitset](/docs/ref/std/bitset) | O(cap / 64 + len) to walk | | `DynBitset.first` | [bitset](/docs/ref/std/bitset) | O(cap / 64) | | `DynBitset.full` | [bitset](/docs/ref/std/bitset) | O(cap / 64) time and space | | `DynBitset.intersect` | [bitset](/docs/ref/std/bitset) | O(cap / 64) | | `DynBitset.is_empty` | [bitset](/docs/ref/std/bitset) | O(1) | | `DynBitset.last` | [bitset](/docs/ref/std/bitset) | O(cap / 64) | | `DynBitset.len` | [bitset](/docs/ref/std/bitset) | O(1) | | `DynBitset.meets` | [bitset](/docs/ref/std/bitset) | O(cap / 64), less on an early hit | | `DynBitset.new` | [bitset](/docs/ref/std/bitset) | O(cap / 64) time and space | | `DynBitset.next` | [bitset](/docs/ref/std/bitset) | O(cap / 64) | | `DynBitset.nth` | [bitset](/docs/ref/std/bitset) | O(cap / 64) | | `DynBitset.prev` | [bitset](/docs/ref/std/bitset) | O(cap / 64) | | `DynBitset.recount` | [bitset](/docs/ref/std/bitset) | | | `DynBitset.remove` | [bitset](/docs/ref/std/bitset) | O(1) | | `DynBitset.resize` | [bitset](/docs/ref/std/bitset) | O(new_cap / 64) time and space | | `DynBitset.set` | [bitset](/docs/ref/std/bitset) | O(1) | | `DynBitset.shift_down` | [bitset](/docs/ref/std/bitset) | O(cap / 64) | | `DynBitset.shift_or` | [bitset](/docs/ref/std/bitset) | O(cap / 64) | | `DynBitset.shift_up` | [bitset](/docs/ref/std/bitset) | O(cap / 64) | | `DynBitset.subset_sums` | [bitset](/docs/ref/std/bitset) | O(cap sqrt(S) / 64) time, where S is the sum of `weights`; O(cap / 64) space | | `DynBitset.subtract` | [bitset](/docs/ref/std/bitset) | O(cap / 64) | | `DynBitset.symmetric` | [bitset](/docs/ref/std/bitset) | O(cap / 64) | | `DynBitset.toggle` | [bitset](/docs/ref/std/bitset) | O(1) | | `DynBitset.trim` | [bitset](/docs/ref/std/bitset) | | | `DynBitset.union` | [bitset](/docs/ref/std/bitset) | O(cap / 64) | | `Edge` | [graph](/docs/ref/std/graph) | | | `Edged` | [graph](/docs/ref/std/graph) | | | `Edged.e` | [graph](/docs/ref/std/graph) | O(1) | | `EdgedNext` | [graph](/docs/ref/std/graph) | | | `ErasableHeap` | [heap](/docs/ref/std/heap) | | | `ErasableHeap.clear` | [heap](/docs/ref/std/heap) | O(1) | | `ErasableHeap.is_empty` | [heap](/docs/ref/std/heap) | O(1) | | `ErasableHeap.len` | [heap](/docs/ref/std/heap) | O(1) | | `ErasableHeap.new` | [heap](/docs/ref/std/heap) | O(1) | | `ErasableHeap.peek` | [heap](/docs/ref/std/heap) | O(log n) amortized | | `ErasableHeap.pop` | [heap](/docs/ref/std/heap) | O(log n) amortized | | `ErasableHeap.prune` | [heap](/docs/ref/std/heap) | | | `ErasableHeap.push` | [heap](/docs/ref/std/heap) | O(log n) | | `ErasableHeap.remove` | [heap](/docs/ref/std/heap) | O(log n) | | `ErasableHeap.take` | [heap](/docs/ref/std/heap) | O(1) | | `EulerTourTree` | [tree](/docs/ref/std/tree) | | | `EulerTourTree.connected` | [tree](/docs/ref/std/tree) | expected O(log n) | | `EulerTourTree.cut` | [tree](/docs/ref/std/tree) | expected O(log n) | | `EulerTourTree.fold_sub` | [tree](/docs/ref/std/tree) | expected O(log n) | | `EulerTourTree.fold_tree` | [tree](/docs/ref/std/tree) | expected O(log n) | | `EulerTourTree.get` | [tree](/docs/ref/std/tree) | O(1) | | `EulerTourTree.len` | [tree](/docs/ref/std/tree) | expected O(log n) | | `EulerTourTree.link` | [tree](/docs/ref/std/tree) | expected O(log n) | | `EulerTourTree.new` | [tree](/docs/ref/std/tree) | O(n) | | `EulerTourTree.set` | [tree](/docs/ref/std/tree) | expected O(log n) | | `Events` | [tree](/docs/ref/std/tree) | | | `Events.enter` | [tree](/docs/ref/std/tree) | O(1) | | `Events.exit` | [tree](/docs/ref/std/tree) | O(1) | | `Events.path` | [tree](/docs/ref/std/tree) | O(log n) | | `Events.sub` | [tree](/docs/ref/std/tree) | O(1) | | `Fenwick` | [fenwick](/docs/ref/std/fenwick) | | | `Fenwick.add` | [fenwick](/docs/ref/std/fenwick) | O(log \|D\|) | | `Fenwick.all` | [fenwick](/docs/ref/std/fenwick) | O(1) | | `Fenwick.clear` | [fenwick](/docs/ref/std/fenwick) | O(\|D\|) | | `Fenwick.first_ge` | [fenwick](/docs/ref/std/fenwick) | O(log \|D\|) | | `Fenwick.first_gt` | [fenwick](/docs/ref/std/fenwick) | O(log \|D\|) | | `Fenwick.fold` | [fenwick](/docs/ref/std/fenwick) | O(log \|D\|) | | `Fenwick.get` | [fenwick](/docs/ref/std/fenwick) | O(log \|D\|) | | `Fenwick.kth` | [fenwick](/docs/ref/std/fenwick) | O(log \|D\|) | | `Fenwick.new` | [fenwick](/docs/ref/std/fenwick) | O(\|D\|) time; memory \|D\| + 1 values | | `Fenwick.prefix` | [fenwick](/docs/ref/std/fenwick) | O(log \|D\|) | | `Fenwick.set` | [fenwick](/docs/ref/std/fenwick) | O(log \|D\|) | | `Fenwick.suffix` | [fenwick](/docs/ref/std/fenwick) | O(log \|D\|) | | `Fenwick2D` | [fenwick](/docs/ref/std/fenwick) | | | `Fenwick2D.add` | [fenwick](/docs/ref/std/fenwick) | O(log \|R\| log \|C\|) | | `Fenwick2D.clear` | [fenwick](/docs/ref/std/fenwick) | O(\|R\| \|C\|) | | `Fenwick2D.corner` | [fenwick](/docs/ref/std/fenwick) | | | `Fenwick2D.fold` | [fenwick](/docs/ref/std/fenwick) | O(log \|R\| log \|C\|) | | `Fenwick2D.get` | [fenwick](/docs/ref/std/fenwick) | O(log \|R\| log \|C\|) | | `Fenwick2D.new` | [fenwick](/docs/ref/std/fenwick) | O(\|R\| \|C\|) time; memory (\|R\| + 1)(\|C\| + 1) values | | `Fenwick2D.prefix` | [fenwick](/docs/ref/std/fenwick) | O(log \|R\| log \|C\|) | | `FillOrder` | [prefix](/docs/ref/std/prefix) | | | `FillPrefix` | [prefix](/docs/ref/std/prefix) | | | `FillPrefix.fold` | [prefix](/docs/ref/std/prefix) | O(1) | | `FillPrefix.prefix` | [prefix](/docs/ref/std/prefix) | O(1) | | `FillPrefix.set` | [prefix](/docs/ref/std/prefix) | O(1) | | `Filtered` | [seq](/docs/ref/std/seq) | | | `Filtered.src` | [seq](/docs/ref/std/seq) | O(1) | | `FlatMap` | [hashmap](/docs/ref/std/hashmap) | | | `FlatMap.absorb` | [hashmap](/docs/ref/std/hashmap) | O(min(\|self\|, \|other\|)) expected | | `FlatMap.clear` | [hashmap](/docs/ref/std/hashmap) | O(capacity) | | `FlatMap.contains` | [hashmap](/docs/ref/std/hashmap) | O(1) expected | | `FlatMap.get` | [hashmap](/docs/ref/std/hashmap) | O(1) expected | | `FlatMap.get_or_insert` | [hashmap](/docs/ref/std/hashmap) | O(1) expected amortized | | `FlatMap.is_empty` | [hashmap](/docs/ref/std/hashmap) | O(1) | | `FlatMap.items` | [hashmap](/docs/ref/std/hashmap) | O(1) to make, O(capacity) to walk | | `FlatMap.keys` | [hashmap](/docs/ref/std/hashmap) | O(1) to make, O(capacity) to walk | | `FlatMap.len` | [hashmap](/docs/ref/std/hashmap) | O(1) | | `FlatMap.new` | [hashmap](/docs/ref/std/hashmap) | O(cap) | | `FlatMap.rehash` | [hashmap](/docs/ref/std/hashmap) | | | `FlatMap.remove` | [hashmap](/docs/ref/std/hashmap) | O(1) expected | | `FlatMap.reserve` | [hashmap](/docs/ref/std/hashmap) | O(cap) when the table grows, O(1) otherwise | | `FlatMap.set` | [hashmap](/docs/ref/std/hashmap) | O(1) expected amortized | | `FlatMap.slot` | [hashmap](/docs/ref/std/hashmap) | | | `FlatMap.take` | [hashmap](/docs/ref/std/hashmap) | O(1) | | `FlatMap.values` | [hashmap](/docs/ref/std/hashmap) | O(1) to make, O(capacity) to walk | | `Flip` | [lazy](/docs/ref/std/lazy) | | | `Flip.of` | [lazy](/docs/ref/std/lazy) | O(1) | | `Flip.op` | [lazy](/docs/ref/std/lazy) | O(1) | | `FlipAction` | [algebra](/docs/ref/std/algebra) | | | `FlowGraph` | [flow](/docs/ref/std/flow) | | | `FlowGraph.add` | [flow](/docs/ref/std/flow) | O(1) amortized; two arcs of memory | | `FlowGraph.add_both` | [flow](/docs/ref/std/flow) | O(1) amortized; two arcs of memory | | `FlowGraph.arcs` | [flow](/docs/ref/std/flow) | O(E) for the whole walk | | `FlowGraph.augment` | [flow](/docs/ref/std/flow) | | | `FlowGraph.cap` | [flow](/docs/ref/std/flow) | O(1) | | `FlowGraph.close` | [flow](/docs/ref/std/flow) | | | `FlowGraph.cut_arcs` | [flow](/docs/ref/std/flow) | O(V + E) | | `FlowGraph.flow` | [flow](/docs/ref/std/flow) | O(1) | | `FlowGraph.levels` | [flow](/docs/ref/std/flow) | | | `FlowGraph.max_flow` | [flow](/docs/ref/std/flow) | O(V² E); O(E sqrt V) when every capacity is 1 | | `FlowGraph.min_cut` | [flow](/docs/ref/std/flow) | O(V + E) | | `FlowGraph.new` | [flow](/docs/ref/std/flow) | O(n) for n = `V.count` | | `FlowGraph.out` | [flow](/docs/ref/std/flow) | O(deg u) for the whole walk | | `FlowGraph.paths` | [flow](/docs/ref/std/flow) | O(P (V + E)) for P paths | | `FlowGraph.push` | [flow](/docs/ref/std/flow) | | | `FlowGraph.push_relabel` | [flow](/docs/ref/std/flow) | O(V² sqrt E) | | `FlowGraph.reset` | [flow](/docs/ref/std/flow) | O(E) | | `FlowGraph.residual` | [flow](/docs/ref/std/flow) | O(1) | | `FlowGraph.set_cap` | [flow](/docs/ref/std/flow) | O(1) | | `FlowGraph.source` | [flow](/docs/ref/std/flow) | O(1) | | `FlowGraph.target` | [flow](/docs/ref/std/flow) | O(1) | | `Functional` | [graph](/docs/ref/std/graph) | | | `Functional.after` | [graph](/docs/ref/std/graph) | O(log k) | | `Functional.cycle_len` | [graph](/docs/ref/std/graph) | O(1) | | `Functional.cycles` | [graph](/docs/ref/std/graph) | O(n) | | `Functional.depth` | [graph](/docs/ref/std/graph) | O(1) | | `Functional.dist` | [graph](/docs/ref/std/graph) | O(log n) | | `Functional.jump_while` | [graph](/docs/ref/std/graph) | O(log n) | | `Functional.lift` | [graph](/docs/ref/std/graph) | | | `Functional.new` | [graph](/docs/ref/std/graph) | O(n log n) | | `Functional.on_cycle` | [graph](/docs/ref/std/graph) | O(1) | | `Functional.root_of` | [graph](/docs/ref/std/graph) | O(1) | | `Graph` | [graph](/docs/ref/std/graph) | | | `Graph.at` | [graph](/docs/ref/std/graph) | O(1) | | `Graph.deg` | [graph](/docs/ref/std/graph) | O(1) | | `Graph.dfs_tree` | [graph](/docs/ref/std/graph) | O(n + m) | | `Graph.directed` | [graph](/docs/ref/std/graph) | O(n + m) time and memory, plus `m` calls of `keep` | | `Graph.edges` | [graph](/docs/ref/std/graph) | O(1) to make, O(1) per edge | | `Graph.has` | [graph](/docs/ref/std/graph) | O(deg u) | | `Graph.hops` | [graph](/docs/ref/std/graph) | O(n (n + m)) time, O(n^2) memory | | `Graph.lists` | [graph](/docs/ref/std/graph) | O(n + m) | | `Graph.matrix` | [graph](/docs/ref/std/graph) | O(n^2 + m) time, O(n^2) memory | | `Graph.next` | [graph](/docs/ref/std/graph) | O(1) per vertex yielded | | `Graph.of` | [graph](/docs/ref/std/graph) | O(n + m) | | `Graph.only` | [graph](/docs/ref/std/graph) | O(1) to make; `keep` and `from` run per arc walked | | `Graph.out` | [graph](/docs/ref/std/graph) | O(1) to make, O(1) per arc | | `Graph.peel` | [graph](/docs/ref/std/graph) | O(n + m) plus the calls of `ready` and `on_remove` | | `Graph.spanning_tree` | [graph](/docs/ref/std/graph) | O(n + m) | | `Graph.transpose` | [graph](/docs/ref/std/graph) | O(n + m) | | `Graph.undirected` | [graph](/docs/ref/std/graph) | O(n + m) time and memory, plus `2m` calls of `keep` | | `Graph.weighted` | [graph](/docs/ref/std/graph) | O(1) to make; `f` runs on every arc read | | `GraphicMatroid` | [flow](/docs/ref/std/flow) | | | `GraphicMatroid.new` | [flow](/docs/ref/std/flow) | O(1); each `rebuild` is O(E alpha(V)) | | `Group` | [algebra](/docs/ref/std/algebra) | | | `Group.of` | [algebra](/docs/ref/std/algebra) | O(1) | | `HalfPlane` | [geometry](/docs/ref/std/geometry) | | | `HalfPlane.from_line` | [geometry](/docs/ref/std/geometry) | O(1) | | `HalfPlane.side` | [geometry](/docs/ref/std/geometry) | O(1) | | `HalfPlane.through` | [geometry](/docs/ref/std/geometry) | O(1) | | `Hash2D` | [strings](/docs/ref/std/strings) | | | `Hash2D.new` | [strings](/docs/ref/std/strings) | | | `Hash2D.rect` | [strings](/docs/ref/std/strings) | | | `Hash61` | [strings](/docs/ref/std/strings) | | | `Hashable` | [strings](/docs/ref/std/strings) | | | `Hashable.hash_token` | [strings](/docs/ref/std/strings) | | | `HashVal` | [strings](/docs/ref/std/strings) | | | `HashVal.hash_token` | [strings](/docs/ref/std/strings) | O(1) | | `HasId` | [algebra](/docs/ref/std/algebra) | | | `HasId.id` | [algebra](/docs/ref/std/algebra) | | | `HasInv` | [algebra](/docs/ref/std/algebra) | | | `HasInv.inv` | [algebra](/docs/ref/std/algebra) | | | `Heap` | [heap](/docs/ref/std/heap) | | | `Heap.clear` | [heap](/docs/ref/std/heap) | O(1) | | `Heap.drain` | [heap](/docs/ref/std/heap) | O(log n) per step | | `Heap.is_empty` | [heap](/docs/ref/std/heap) | O(1) | | `Heap.len` | [heap](/docs/ref/std/heap) | O(1) | | `Heap.less` | [heap](/docs/ref/std/heap) | | | `Heap.new` | [heap](/docs/ref/std/heap) | O(1) | | `Heap.of` | [heap](/docs/ref/std/heap) | O(n) | | `Heap.peek` | [heap](/docs/ref/std/heap) | O(1) | | `Heap.pop` | [heap](/docs/ref/std/heap) | O(log n) | | `Heap.push` | [heap](/docs/ref/std/heap) | O(log n), amortized over list growth | | `Heap.push_all` | [heap](/docs/ref/std/heap) | O(k log n) for `k` items | | `Heap.push_pop` | [heap](/docs/ref/std/heap) | O(log n); O(1) when `x` is returned | | `Heap.replace_top` | [heap](/docs/ref/std/heap) | O(log n) | | `Heap.reserve` | [heap](/docs/ref/std/heap) | O(cap) when the storage grows, O(1) otherwise | | `Heap.sift_down` | [heap](/docs/ref/std/heap) | | | `Heap.take` | [heap](/docs/ref/std/heap) | O(1) | | `HistoricBeatsSegTree` | [beats](/docs/ref/std/beats) | | | `HistoricBeatsSegTree.add` | [beats](/docs/ref/std/beats) | O(log \|D\|) | | `HistoricBeatsSegTree.apply` | [beats](/docs/ref/std/beats) | | | `HistoricBeatsSegTree.ask` | [beats](/docs/ref/std/beats) | | | `HistoricBeatsSegTree.build` | [beats](/docs/ref/std/beats) | | | `HistoricBeatsSegTree.chmax` | [beats](/docs/ref/std/beats) | O(log \|D\|) amortized; O(log^2 \|D\|) amortized when mixed with `add` | | `HistoricBeatsSegTree.chmin` | [beats](/docs/ref/std/beats) | O(log \|D\|) amortized; O(log^2 \|D\|) amortized when mixed with `add` | | `HistoricBeatsSegTree.compose` | [beats](/docs/ref/std/beats) | | | `HistoricBeatsSegTree.give` | [beats](/docs/ref/std/beats) | | | `HistoricBeatsSegTree.hist_max` | [beats](/docs/ref/std/beats) | O(log \|D\|) | | `HistoricBeatsSegTree.hist_sum` | [beats](/docs/ref/std/beats) | O(log \|D\|) | | `HistoricBeatsSegTree.max_val` | [beats](/docs/ref/std/beats) | O(log \|D\|) | | `HistoricBeatsSegTree.new` | [beats](/docs/ref/std/beats) | O(\|D\|) | | `HistoricBeatsSegTree.pull` | [beats](/docs/ref/std/beats) | | | `HistoricBeatsSegTree.push` | [beats](/docs/ref/std/beats) | | | `HistoricBeatsSegTree.query` | [beats](/docs/ref/std/beats) | | | `HistoricBeatsSegTree.sum` | [beats](/docs/ref/std/beats) | O(log \|D\|) | | `HistoricBeatsSegTree.upd` | [beats](/docs/ref/std/beats) | | | `HistoricBeatsSegTree.update` | [beats](/docs/ref/std/beats) | | | `Id` | [marks](/docs/ref/std/marks) | | | `Idempotent` | [algebra](/docs/ref/std/algebra) | | | `IncrementalBridges` | [graph](/docs/ref/std/graph) | | | `IncrementalBridges.add` | [graph](/docs/ref/std/graph) | O(log n) amortized | | `IncrementalBridges.new` | [graph](/docs/ref/std/graph) | O(n) | | `IncrementalBridges.same` | [graph](/docs/ref/std/graph) | O(alpha) | | `IncrementalBridges.two_edge_same` | [graph](/docs/ref/std/graph) | O(alpha) | | `IndexedHeap` | [heap](/docs/ref/std/heap) | | | `IndexedHeap.before` | [heap](/docs/ref/std/heap) | | | `IndexedHeap.clear` | [heap](/docs/ref/std/heap) | O(len) | | `IndexedHeap.contains` | [heap](/docs/ref/std/heap) | O(1) | | `IndexedHeap.decrease` | [heap](/docs/ref/std/heap) | O(log n) | | `IndexedHeap.get` | [heap](/docs/ref/std/heap) | O(1) | | `IndexedHeap.increase` | [heap](/docs/ref/std/heap) | O(log n) | | `IndexedHeap.is_empty` | [heap](/docs/ref/std/heap) | O(1) | | `IndexedHeap.len` | [heap](/docs/ref/std/heap) | O(1) | | `IndexedHeap.new` | [heap](/docs/ref/std/heap) | O(\|D\|) | | `IndexedHeap.peek` | [heap](/docs/ref/std/heap) | O(1) | | `IndexedHeap.pop` | [heap](/docs/ref/std/heap) | O(log n) | | `IndexedHeap.remove` | [heap](/docs/ref/std/heap) | O(log n) | | `IndexedHeap.set` | [heap](/docs/ref/std/heap) | O(log n) | | `IndexedHeap.sift_down` | [heap](/docs/ref/std/heap) | | | `IndexedHeap.sift_up` | [heap](/docs/ref/std/heap) | | | `IndexedHeap.swap_at` | [heap](/docs/ref/std/heap) | | | `Interner` | [marks](/docs/ref/std/marks) | | | `Interner.clear` | [marks](/docs/ref/std/marks) | O(1) | | `Interner.contains` | [marks](/docs/ref/std/marks) | O(1) expected | | `Interner.get` | [marks](/docs/ref/std/marks) | O(1) expected | | `Interner.id` | [marks](/docs/ref/std/marks) | O(1) expected | | `Interner.is_empty` | [marks](/docs/ref/std/marks) | O(1) | | `Interner.key` | [marks](/docs/ref/std/marks) | O(1) | | `Interner.len` | [marks](/docs/ref/std/marks) | O(1) | | `Interner.new` | [marks](/docs/ref/std/marks) | O(1) | | `Interner.reserve` | [marks](/docs/ref/std/marks) | O(cap) | | `IntervalMap` | [interval](/docs/ref/std/interval) | | | `IntervalMap.assign` | [interval](/docs/ref/std/interval) | O((1 + overwritten) log runs) amortized | | `IntervalMap.assign_point` | [interval](/docs/ref/std/interval) | O(log runs) | | `IntervalMap.each` | [interval](/docs/ref/std/interval) | O(1) per run | | `IntervalMap.each_rev` | [interval](/docs/ref/std/interval) | O(1) per run | | `IntervalMap.first_where` | [interval](/docs/ref/std/interval) | O(log runs + skipped) for `skipped` runs that fail `ok` | | `IntervalMap.from` | [interval](/docs/ref/std/interval) | O(\|D\|) | | `IntervalMap.get` | [interval](/docs/ref/std/interval) | O(log runs) | | `IntervalMap.new` | [interval](/docs/ref/std/interval) | O(1) | | `IntervalMap.range` | [interval](/docs/ref/std/interval) | O(log runs + k) for `k` pieces | | `IntervalMap.run_at` | [interval](/docs/ref/std/interval) | O(log runs) | | `IntervalMap.runs` | [interval](/docs/ref/std/interval) | O(1) | | `IntervalMap.set` | [interval](/docs/ref/std/interval) | O(log runs) | | `IntervalSet` | [interval](/docs/ref/std/interval) | | | `IntervalSet.add` | [interval](/docs/ref/std/interval) | O((1 + merged) log runs) amortized | | `IntervalSet.contains` | [interval](/docs/ref/std/interval) | O(log runs) | | `IntervalSet.contains_range` | [interval](/docs/ref/std/interval) | O(log runs) | | `IntervalSet.covered` | [interval](/docs/ref/std/interval) | O(1) | | `IntervalSet.each` | [interval](/docs/ref/std/interval) | O(1) per run | | `IntervalSet.new` | [interval](/docs/ref/std/interval) | O(1) | | `IntervalSet.next_covered` | [interval](/docs/ref/std/interval) | O(log runs) | | `IntervalSet.next_gap` | [interval](/docs/ref/std/interval) | O(log runs) | | `IntervalSet.remove` | [interval](/docs/ref/std/interval) | O((1 + split) log runs) amortized | | `IntervalSet.run_at` | [interval](/docs/ref/std/interval) | O(log runs) | | `IntervalSet.runs` | [interval](/docs/ref/std/interval) | O(1) | | `io` | [io](/docs/ref/std/io) | | | `Items` | [seq](/docs/ref/std/seq) | | | `Items.src` | [seq](/docs/ref/std/seq) | O(1) | | `JumpTree` | [tree](/docs/ref/std/tree) | | | `JumpTree.add` | [tree](/docs/ref/std/tree) | O(1) | | `JumpTree.ancestor` | [tree](/docs/ref/std/tree) | O(log n) | | `JumpTree.depth` | [tree](/docs/ref/std/tree) | O(1) | | `JumpTree.dist` | [tree](/docs/ref/std/tree) | O(log n) | | `JumpTree.jump` | [tree](/docs/ref/std/tree) | O(log n) | | `JumpTree.jump_while` | [tree](/docs/ref/std/tree) | O(log n) calls of `pred` | | `JumpTree.lca` | [tree](/docs/ref/std/tree) | O(log n) | | `JumpTree.new` | [tree](/docs/ref/std/tree) | O(n) | | `JumpTree.parent` | [tree](/docs/ref/std/tree) | O(1) | | `JumpTree.root_of` | [tree](/docs/ref/std/tree) | O(log n) | | `Keys` | [seq](/docs/ref/std/seq) | | | `KmpAutomaton` | [strings](/docs/ref/std/strings) | | | `KmpAutomaton.find_all` | [strings](/docs/ref/std/strings) | O(\|text\|) | | `KmpAutomaton.len` | [strings](/docs/ref/std/strings) | O(1) | | `KmpAutomaton.link` | [strings](/docs/ref/std/strings) | O(1) | | `KmpAutomaton.new` | [strings](/docs/ref/std/strings) | O(\|pat\| * \|A\|) | | `KmpAutomaton.step` | [strings](/docs/ref/std/strings) | O(1) | | `KruskalTree` | [tree](/docs/ref/std/tree) | | | `KruskalTree.bottleneck` | [tree](/docs/ref/std/tree) | O(log n) | | `KruskalTree.reach` | [tree](/docs/ref/std/tree) | O(log n) | | `KruskalTree.top` | [tree](/docs/ref/std/tree) | O(log n) calls of `ok` | | `KruskalTree.tree` | [tree](/docs/ref/std/tree) | O(1); built with the tree | | `KruskalTree.up` | [tree](/docs/ref/std/tree) | O(n) calls of `op` and `leaf` | | `Layers` | [tree](/docs/ref/std/tree) | | | `Layers.below` | [tree](/docs/ref/std/tree) | O(log n) | | `Layers.level` | [tree](/docs/ref/std/tree) | O(1) | | `Layers.pos` | [tree](/docs/ref/std/tree) | O(1) | | `LazyEulerTourTree` | [tree](/docs/ref/std/tree) | | | `LazyEulerTourTree.apply_sub` | [tree](/docs/ref/std/tree) | expected O(log n) | | `LazyEulerTourTree.apply_tree` | [tree](/docs/ref/std/tree) | expected O(log n) | | `LazyEulerTourTree.connected` | [tree](/docs/ref/std/tree) | expected O(log n) | | `LazyEulerTourTree.cut` | [tree](/docs/ref/std/tree) | expected O(log n) | | `LazyEulerTourTree.fold_sub` | [tree](/docs/ref/std/tree) | expected O(log n) | | `LazyEulerTourTree.fold_tree` | [tree](/docs/ref/std/tree) | expected O(log n) | | `LazyEulerTourTree.get` | [tree](/docs/ref/std/tree) | expected O(log n) | | `LazyEulerTourTree.len` | [tree](/docs/ref/std/tree) | expected O(log n) | | `LazyEulerTourTree.link` | [tree](/docs/ref/std/tree) | expected O(log n) | | `LazyEulerTourTree.new` | [tree](/docs/ref/std/tree) | O(n) | | `LazyEulerTourTree.set` | [tree](/docs/ref/std/tree) | expected O(log n) | | `LazyLinkCut` | [tree](/docs/ref/std/tree) | | | `LazyLinkCut.access` | [tree](/docs/ref/std/tree) | | | `LazyLinkCut.apply_path` | [tree](/docs/ref/std/tree) | amortized O(log n) | | `LazyLinkCut.connected` | [tree](/docs/ref/std/tree) | amortized O(log n) | | `LazyLinkCut.cut` | [tree](/docs/ref/std/tree) | amortized O(log n) | | `LazyLinkCut.dist` | [tree](/docs/ref/std/tree) | amortized O(log n) | | `LazyLinkCut.fold_path` | [tree](/docs/ref/std/tree) | amortized O(log n) | | `LazyLinkCut.get` | [tree](/docs/ref/std/tree) | amortized O(log n) | | `LazyLinkCut.jump` | [tree](/docs/ref/std/tree) | amortized O(log n) | | `LazyLinkCut.lca` | [tree](/docs/ref/std/tree) | amortized O(log n) | | `LazyLinkCut.link` | [tree](/docs/ref/std/tree) | amortized O(log n), with one `root_of` to check the trees differ | | `LazyLinkCut.make_root` | [tree](/docs/ref/std/tree) | amortized O(log n) | | `LazyLinkCut.new` | [tree](/docs/ref/std/tree) | O(n) | | `LazyLinkCut.pull` | [tree](/docs/ref/std/tree) | | | `LazyLinkCut.push` | [tree](/docs/ref/std/tree) | | | `LazyLinkCut.put` | [tree](/docs/ref/std/tree) | | | `LazyLinkCut.root_of` | [tree](/docs/ref/std/tree) | amortized O(log n) | | `LazyLinkCut.rotate` | [tree](/docs/ref/std/tree) | | | `LazyLinkCut.set` | [tree](/docs/ref/std/tree) | amortized O(log n) | | `LazyLinkCut.splay` | [tree](/docs/ref/std/tree) | | | `LazyLinkCut.top` | [tree](/docs/ref/std/tree) | | | `LazyLinkCut.turn` | [tree](/docs/ref/std/tree) | | | `LazyTreap` | [lazy](/docs/ref/std/lazy) | | | `LazyTreap.append` | [lazy](/docs/ref/std/lazy) | O(log n) expected | | `LazyTreap.apply` | [lazy](/docs/ref/std/lazy) | O(log n) expected | | `LazyTreap.apply_all` | [lazy](/docs/ref/std/lazy) | O(1) | | `LazyTreap.apply_range` | [lazy](/docs/ref/std/lazy) | O(log n) expected | | `LazyTreap.copy_from` | [lazy](/docs/ref/std/lazy) | | | `LazyTreap.down` | [lazy](/docs/ref/std/lazy) | | | `LazyTreap.erase_at` | [lazy](/docs/ref/std/lazy) | O(log n) expected | | `LazyTreap.erase_range` | [lazy](/docs/ref/std/lazy) | O(log n) expected | | `LazyTreap.get` | [lazy](/docs/ref/std/lazy) | O(log n) expected | | `LazyTreap.ins` | [lazy](/docs/ref/std/lazy) | | | `LazyTreap.insert` | [lazy](/docs/ref/std/lazy) | O(log n) expected | | `LazyTreap.insert_at` | [lazy](/docs/ref/std/lazy) | O(log n) expected | | `LazyTreap.is_empty` | [lazy](/docs/ref/std/lazy) | O(1) | | `LazyTreap.len` | [lazy](/docs/ref/std/lazy) | O(1) | | `LazyTreap.merge` | [lazy](/docs/ref/std/lazy) | | | `LazyTreap.new` | [lazy](/docs/ref/std/lazy) | O(1) | | `LazyTreap.priority` | [lazy](/docs/ref/std/lazy) | | | `LazyTreap.pull` | [lazy](/docs/ref/std/lazy) | | | `LazyTreap.push` | [lazy](/docs/ref/std/lazy) | O(log n) expected | | `LazyTreap.put` | [lazy](/docs/ref/std/lazy) | | | `LazyTreap.reserve` | [lazy](/docs/ref/std/lazy) | O(n) when it grows, else O(1) | | `LazyTreap.reverse` | [lazy](/docs/ref/std/lazy) | O(log n) expected | | `LazyTreap.split_at` | [lazy](/docs/ref/std/lazy) | O(log n) expected | | `LazyTreap.split_pos` | [lazy](/docs/ref/std/lazy) | | | `LazyTreap.split_val` | [lazy](/docs/ref/std/lazy) | | | `LazyTreap.sz_of` | [lazy](/docs/ref/std/lazy) | | | `LazyTreap.take` | [lazy](/docs/ref/std/lazy) | O(k + log n) | | `LazyTreap.to_list` | [lazy](/docs/ref/std/lazy) | O(n) | | `LazyTreap.walk` | [lazy](/docs/ref/std/lazy) | | | `LcaTable` | [tree](/docs/ref/std/tree) | | | `LcaTable.dist` | [tree](/docs/ref/std/tree) | O(1) | | `LcaTable.lca` | [tree](/docs/ref/std/tree) | O(1) | | `LcaTable.new` | [tree](/docs/ref/std/tree) | O(n log n) time and memory | | `LiChao` | [dp](/docs/ref/std/dp) | | | `LiChao.add` | [dp](/docs/ref/std/dp) | O(log n) for a whole line, O(log^2 n) on a segment, for n = `over.len`; at most one new cell per level | | `LiChao.at` | [dp](/docs/ref/std/dp) | O(log n) for n = `over.len` | | `LiChao.clear` | [dp](/docs/ref/std/dp) | O(1) amortized | | `LiChao.kid` | [dp](/docs/ref/std/dp) | | | `LiChao.line_at` | [dp](/docs/ref/std/dp) | O(log n) for n = `over.len` | | `LiChao.new` | [dp](/docs/ref/std/dp) | O(1) | | `LiChao.settle` | [dp](/docs/ref/std/dp) | | | `LiChao.wins` | [dp](/docs/ref/std/dp) | | | `Lift` | [tree](/docs/ref/std/tree) | | | `Lift.ancestor` | [tree](/docs/ref/std/tree) | O(log n) | | `Lift.climb` | [tree](/docs/ref/std/tree) | O(log n) calls of `ok` | | `Lift.climb_while` | [tree](/docs/ref/std/tree) | O(log n) calls of `ok` and `op` | | `Lift.depth` | [tree](/docs/ref/std/tree) | O(1) | | `Lift.fold` | [tree](/docs/ref/std/tree) | O(log n) calls of `op` | | `Lift.lca` | [tree](/docs/ref/std/tree) | O(log n) | | `Lift.new` | [tree](/docs/ref/std/tree) | O(n log n) time and memory | | `Lift.of` | [tree](/docs/ref/std/tree) | O(n log n) time and memory, n calls of `next` | | `Lift.parent` | [tree](/docs/ref/std/tree) | O(1) | | `Line` | [dp](/docs/ref/std/dp) | | | `Line.at` | [dp](/docs/ref/std/dp) | O(1) | | `LinearRmq` | [sparse](/docs/ref/std/sparse) | | | `LinearRmq.argbest` | [sparse](/docs/ref/std/sparse) | O(1) | | `LinearRmq.best` | [sparse](/docs/ref/std/sparse) | O(1) | | `LinearRmq.better` | [sparse](/docs/ref/std/sparse) | | | `LinearRmq.in_block` | [sparse](/docs/ref/std/sparse) | | | `LinearRmq.new` | [sparse](/docs/ref/std/sparse) | O(\|D\|) time and memory | | `LinearRmq.try_best` | [sparse](/docs/ref/std/sparse) | O(1) | | `LineContainer` | [dp](/docs/ref/std/dp) | | | `LineContainer.add` | [dp](/docs/ref/std/dp) | O(log n) amortized | | `LineContainer.at` | [dp](/docs/ref/std/dp) | O(log n) | | `LineContainer.best` | [dp](/docs/ref/std/dp) | | | `LineContainer.drop_end` | [dp](/docs/ref/std/dp) | | | `LineContainer.end` | [dp](/docs/ref/std/dp) | | | `LineContainer.floor_div` | [dp](/docs/ref/std/dp) | | | `LineContainer.len` | [dp](/docs/ref/std/dp) | O(1) | | `LineContainer.line_at` | [dp](/docs/ref/std/dp) | O(log n) | | `LineContainer.meet` | [dp](/docs/ref/std/dp) | | | `LineContainer.merge` | [dp](/docs/ref/std/dp) | | | `LineContainer.sign` | [dp](/docs/ref/std/dp) | | | `LineContainer.split` | [dp](/docs/ref/std/dp) | | | `LinkCut` | [tree](/docs/ref/std/tree) | | | `LinkCut.access` | [tree](/docs/ref/std/tree) | | | `LinkCut.connected` | [tree](/docs/ref/std/tree) | amortized O(log n) | | `LinkCut.cut` | [tree](/docs/ref/std/tree) | amortized O(log n) | | `LinkCut.dist` | [tree](/docs/ref/std/tree) | amortized O(log n) | | `LinkCut.fold_path` | [tree](/docs/ref/std/tree) | amortized O(log n) | | `LinkCut.get` | [tree](/docs/ref/std/tree) | O(1) | | `LinkCut.jump` | [tree](/docs/ref/std/tree) | amortized O(log n) | | `LinkCut.lca` | [tree](/docs/ref/std/tree) | amortized O(log n) | | `LinkCut.link` | [tree](/docs/ref/std/tree) | amortized O(log n), with one `root_of` to check the trees differ | | `LinkCut.make_root` | [tree](/docs/ref/std/tree) | amortized O(log n) | | `LinkCut.new` | [tree](/docs/ref/std/tree) | O(n) | | `LinkCut.pull` | [tree](/docs/ref/std/tree) | | | `LinkCut.push` | [tree](/docs/ref/std/tree) | | | `LinkCut.root_of` | [tree](/docs/ref/std/tree) | amortized O(log n) | | `LinkCut.rotate` | [tree](/docs/ref/std/tree) | | | `LinkCut.set` | [tree](/docs/ref/std/tree) | amortized O(log n) | | `LinkCut.splay` | [tree](/docs/ref/std/tree) | | | `LinkCut.top` | [tree](/docs/ref/std/tree) | | | `LinkCut.turn` | [tree](/docs/ref/std/tree) | | | `LinkedList` | [deque](/docs/ref/std/deque) | | | `LinkedList.bwd` | [deque](/docs/ref/std/deque) | | | `LinkedList.clear` | [deque](/docs/ref/std/deque) | O(1) | | `LinkedList.each` | [deque](/docs/ref/std/deque) | O(1) per step | | `LinkedList.each_rev` | [deque](/docs/ref/std/deque) | O(1) per step | | `LinkedList.first` | [deque](/docs/ref/std/deque) | O(1) | | `LinkedList.from_list` | [deque](/docs/ref/std/deque) | O(n) | | `LinkedList.fwd` | [deque](/docs/ref/std/deque) | | | `LinkedList.is_empty` | [deque](/docs/ref/std/deque) | O(1) | | `LinkedList.last` | [deque](/docs/ref/std/deque) | O(1) | | `LinkedList.len` | [deque](/docs/ref/std/deque) | O(1) | | `LinkedList.new` | [deque](/docs/ref/std/deque) | O(1) | | `LinkedList.node` | [deque](/docs/ref/std/deque) | | | `LinkedList.of` | [deque](/docs/ref/std/deque) | O(1) | | `LinkedList.pop` | [deque](/docs/ref/std/deque) | O(1) | | `LinkedList.pop_front` | [deque](/docs/ref/std/deque) | O(1) | | `LinkedList.push` | [deque](/docs/ref/std/deque) | O(1) | | `LinkedList.push_front` | [deque](/docs/ref/std/deque) | O(1) | | `LinkedList.reverse` | [deque](/docs/ref/std/deque) | O(1) | | `LinkedList.set_bwd` | [deque](/docs/ref/std/deque) | | | `LinkedList.set_fwd` | [deque](/docs/ref/std/deque) | | | `LinkedList.splice_back` | [deque](/docs/ref/std/deque) | O(1) | | `LinkedList.splice_front` | [deque](/docs/ref/std/deque) | O(1) | | `Lit` | [graph](/docs/ref/std/graph) | | | `Lit.flip` | [graph](/docs/ref/std/graph) | O(1) | | `Location` | [geometry](/docs/ref/std/geometry) | | | `LongPaths` | [tree](/docs/ref/std/tree) | | | `LongPaths.slot` | [tree](/docs/ref/std/tree) | O(1) | | `LongPaths.slots` | [tree](/docs/ref/std/tree) | O(1) | | `Mapped` | [seq](/docs/ref/std/seq) | | | `Mapped.src` | [seq](/docs/ref/std/seq) | O(1) | | `Mark` | [dsu](/docs/ref/std/dsu) | | | `MarkMap` | [marks](/docs/ref/std/marks) | | | `MarkMap.clear` | [marks](/docs/ref/std/marks) | O(1) amortized; O(\|D\|) on the call that wraps the counter | | `MarkMap.contains` | [marks](/docs/ref/std/marks) | O(1) | | `MarkMap.get` | [marks](/docs/ref/std/marks) | O(1) | | `MarkMap.is_empty` | [marks](/docs/ref/std/marks) | O(1) | | `MarkMap.len` | [marks](/docs/ref/std/marks) | O(1) | | `MarkMap.new` | [marks](/docs/ref/std/marks) | O(\|D\|) | | `MarkMap.remove` | [marks](/docs/ref/std/marks) | O(1) | | `MarkMap.set` | [marks](/docs/ref/std/marks) | O(1) | | `Marks` | [marks](/docs/ref/std/marks) | | | `Marks.add` | [marks](/docs/ref/std/marks) | O(1) | | `Marks.clear` | [marks](/docs/ref/std/marks) | O(1) amortized; O(\|D\|) on the call that wraps the counter | | `Marks.contains` | [marks](/docs/ref/std/marks) | O(1) | | `Marks.is_empty` | [marks](/docs/ref/std/marks) | O(1) | | `Marks.len` | [marks](/docs/ref/std/marks) | O(1) | | `Marks.new` | [marks](/docs/ref/std/marks) | O(\|D\|) | | `Marks.remove` | [marks](/docs/ref/std/marks) | O(1) | | `Mat` | [matrix](/docs/ref/std/matrix) | | | `Mat.adjugate` | [matrix](/docs/ref/std/matrix) | O(n^3) time, O(n^2) space | | `Mat.at` | [matrix](/docs/ref/std/matrix) | O(1) | | `Mat.char_poly` | [matrix](/docs/ref/std/matrix) | O(n^3) time, O(n^2) space | | `Mat.det` | [matrix](/docs/ref/std/matrix) | O(n^3) time, O(n^2) space | | `Mat.det_mod` | [matrix](/docs/ref/std/matrix) | O(n^3 log m) | | `Mat.filled` | [matrix](/docs/ref/std/matrix) | O(rows * cols) time and space | | `Mat.from_flat` | [matrix](/docs/ref/std/matrix) | O(rows * cols) time and space | | `Mat.from_rows` | [matrix](/docs/ref/std/matrix) | O(rows * cols) time and space | | `Mat.get` | [matrix](/docs/ref/std/matrix) | O(1) | | `Mat.identity` | [matrix](/docs/ref/std/matrix) | O(n^2) time and space | | `Mat.inverse` | [matrix](/docs/ref/std/matrix) | O(n^3) time, O(n^2) space | | `Mat.mul_vec` | [matrix](/docs/ref/std/matrix) | O(rows * cols) time, O(rows) space | | `Mat.new` | [matrix](/docs/ref/std/matrix) | O(rows * cols) time and space | | `Mat.pfaffian` | [matrix](/docs/ref/std/matrix) | O(n^3) time, O(n^2) space | | `Mat.product` | [matrix](/docs/ref/std/matrix) | O(n^2) time and space (for the identity) | | `Mat.rank` | [matrix](/docs/ref/std/matrix) | O(rows * cols * min(rows, cols)) time, O(rows * cols) space | | `Mat.rref` | [matrix](/docs/ref/std/matrix) | O(rows * cols * min(rows, cols)) time, O(rows * cols) space | | `Mat.set` | [matrix](/docs/ref/std/matrix) | O(1) | | `Mat.solve` | [matrix](/docs/ref/std/matrix) | O(rows * cols * min(rows, cols)) time, O(rows * cols) space | | `Mat.solve_space` | [matrix](/docs/ref/std/matrix) | O(rows * cols * min(rows, cols)) time, O(rows * cols) space | | `Mat.transpose` | [matrix](/docs/ref/std/matrix) | O(rows * cols) time and space | | `Mat.zeros` | [matrix](/docs/ref/std/matrix) | O(rows * cols) time and space | | `Mat.add` | [matrix](/docs/ref/std/matrix) | | | `Mat.mul` | [matrix](/docs/ref/std/matrix) | | | `Mat.pow` | [matrix](/docs/ref/std/matrix) | | | `Mat.sub` | [matrix](/docs/ref/std/matrix) | | | `Matching` | [flow](/docs/ref/std/flow) | | | `Matching.add` | [flow](/docs/ref/std/flow) | O(1) amortized | | `Matching.augment` | [flow](/docs/ref/std/flow) | O(V + E) | | `Matching.augment_all` | [flow](/docs/ref/std/flow) | O(E sqrt V) | | `Matching.back` | [flow](/docs/ref/std/flow) | O(1) | | `Matching.cover` | [flow](/docs/ref/std/flow) | O(V + E) | | `Matching.len` | [flow](/docs/ref/std/flow) | O(1) | | `Matching.mate` | [flow](/docs/ref/std/flow) | O(1) | | `Matching.new` | [flow](/docs/ref/std/flow) | O(L + R) | | `Matching.remove` | [flow](/docs/ref/std/flow) | O(V + E) | | `MatPow` | [matrix](/docs/ref/std/matrix) | | | `MatPow.apply_pow` | [matrix](/docs/ref/std/matrix) | O(n^2 log e) time, O(n) space | | `MatPow.new` | [matrix](/docs/ref/std/matrix) | O(n^3 log max_exp) time, O(n^2 log max_exp) space | | `Matroid` | [flow](/docs/ref/std/flow) | | | `Matroid.can_add` | [flow](/docs/ref/std/flow) | | | `Matroid.can_swap` | [flow](/docs/ref/std/flow) | | | `Matroid.rebuild` | [flow](/docs/ref/std/flow) | | | `MaxCount` | [algebra](/docs/ref/std/algebra) | | | `MaxCount.join` | [algebra](/docs/ref/std/algebra) | O(1) | | `MaxCount.monoid` | [algebra](/docs/ref/std/algebra) | O(1) | | `MaxCount.of` | [algebra](/docs/ref/std/algebra) | O(1) | | `MaxHeap` | [heap](/docs/ref/std/heap) | | | `MaxHeap.clear` | [heap](/docs/ref/std/heap) | O(1) | | `MaxHeap.drain` | [heap](/docs/ref/std/heap) | O(n log n) | | `MaxHeap.is_empty` | [heap](/docs/ref/std/heap) | O(1) | | `MaxHeap.len` | [heap](/docs/ref/std/heap) | O(1) | | `MaxHeap.new` | [heap](/docs/ref/std/heap) | O(1) | | `MaxHeap.of` | [heap](/docs/ref/std/heap) | O(n) | | `MaxHeap.peek` | [heap](/docs/ref/std/heap) | O(1) | | `MaxHeap.pop` | [heap](/docs/ref/std/heap) | O(log n) | | `MaxHeap.push` | [heap](/docs/ref/std/heap) | O(log n) | | `MaxHeap.push_all` | [heap](/docs/ref/std/heap) | O(n + k log(n + k)) | | `MaxHeap.push_pop` | [heap](/docs/ref/std/heap) | O(log n); O(1) when `x` is returned | | `MaxHeap.replace_top` | [heap](/docs/ref/std/heap) | O(log n) | | `MaxHeap.reserve` | [heap](/docs/ref/std/heap) | O(cap) when the storage grows, O(1) otherwise | | `MaxHeap.take` | [heap](/docs/ref/std/heap) | O(1) | | `MaxSub` | [algebra](/docs/ref/std/algebra) | | | `MaxSub.add` | [algebra](/docs/ref/std/algebra) | | | `MaxSub.empty` | [algebra](/docs/ref/std/algebra) | O(1) | | `MaxSub.join` | [algebra](/docs/ref/std/algebra) | O(1) | | `MaxSub.monoid` | [algebra](/docs/ref/std/algebra) | O(1) | | `MaxSub.mul` | [algebra](/docs/ref/std/algebra) | | | `MaxSub.of` | [algebra](/docs/ref/std/algebra) | O(1) | | `MaxSub.rev` | [algebra](/docs/ref/std/algebra) | | | `MaxSub.scale` | [algebra](/docs/ref/std/algebra) | O(1) | | `MaxSub.try_best` | [algebra](/docs/ref/std/algebra) | O(1) | | `MeldHeap` | [heap](/docs/ref/std/heap) | | | `MeldHeap.absorb` | [heap](/docs/ref/std/heap) | O(log n) | | `MeldHeap.add_all` | [heap](/docs/ref/std/heap) | O(1) | | `MeldHeap.clear` | [heap](/docs/ref/std/heap) | O(1) | | `MeldHeap.drain` | [heap](/docs/ref/std/heap) | O(n log n) | | `MeldHeap.is_empty` | [heap](/docs/ref/std/heap) | O(1) | | `MeldHeap.len` | [heap](/docs/ref/std/heap) | O(1) | | `MeldHeap.less` | [heap](/docs/ref/std/heap) | | | `MeldHeap.meld` | [heap](/docs/ref/std/heap) | O(log n) | | `MeldHeap.merge` | [heap](/docs/ref/std/heap) | | | `MeldHeap.new` | [heap](/docs/ref/std/heap) | O(1) | | `MeldHeap.node` | [heap](/docs/ref/std/heap) | | | `MeldHeap.of` | [heap](/docs/ref/std/heap) | O(n) | | `MeldHeap.peek` | [heap](/docs/ref/std/heap) | O(1) | | `MeldHeap.pop` | [heap](/docs/ref/std/heap) | O(log n) | | `MeldHeap.push` | [heap](/docs/ref/std/heap) | O(log n) | | `MeldHeap.push_all` | [heap](/docs/ref/std/heap) | O(k log n) for `k` items | | `MeldHeap.push_down` | [heap](/docs/ref/std/heap) | | | `MeldHeap.rank_of` | [heap](/docs/ref/std/heap) | | | `MeldHeap.take` | [heap](/docs/ref/std/heap) | O(1) | | `MeldHeap.top` | [heap](/docs/ref/std/heap) | O(1) | | `MergeSeg` | [segtree](/docs/ref/std/segtree) | | | `MergeSeg.first_alive` | [segtree](/docs/ref/std/segtree) | O(log \|D\|) amortized | | `MergeSeg.merge` | [segtree](/docs/ref/std/segtree) | O(log \|D\|) amortized per node absorbed | | `MergeSeg.pop_min` | [segtree](/docs/ref/std/segtree) | | | `MergeSeg.push_raw` | [segtree](/docs/ref/std/segtree) | | | `MergeSeg.singleton` | [segtree](/docs/ref/std/segtree) | O(log \|D\|) | | `MergeSortTree` | [segtree](/docs/ref/std/segtree) | | | `MergeSortTree.count_ge` | [segtree](/docs/ref/std/segtree) | O(log^2 \|D\|) | | `MergeSortTree.count_gt` | [segtree](/docs/ref/std/segtree) | O(log^2 \|D\|) | | `MergeSortTree.count_in` | [segtree](/docs/ref/std/segtree) | O(log^2 \|D\|) | | `MergeSortTree.count_le` | [segtree](/docs/ref/std/segtree) | O(log^2 \|D\|) | | `MergeSortTree.count_lt` | [segtree](/docs/ref/std/segtree) | O(log^2 \|D\|) | | `MergeSortTree.first_ge` | [segtree](/docs/ref/std/segtree) | O(log^2 \|D\|) | | `MergeSortTree.last_le` | [segtree](/docs/ref/std/segtree) | O(log^2 \|D\|) | | `MergeSortTree.lower_idx` | [segtree](/docs/ref/std/segtree) | | | `MergeSortTree.new` | [segtree](/docs/ref/std/segtree) | O(\|D\| log \|D\|) time and memory | | `MergeSortTree.upper_idx` | [segtree](/docs/ref/std/segtree) | | | `MinCount` | [algebra](/docs/ref/std/algebra) | | | `MinCount.join` | [algebra](/docs/ref/std/algebra) | O(1) | | `MinCount.monoid` | [algebra](/docs/ref/std/algebra) | O(1) | | `MinCount.of` | [algebra](/docs/ref/std/algebra) | O(1) | | `MinMaxHeap` | [heap](/docs/ref/std/heap) | | | `MinMaxHeap.bubble_up` | [heap](/docs/ref/std/heap) | | | `MinMaxHeap.clear` | [heap](/docs/ref/std/heap) | O(1) | | `MinMaxHeap.first` | [heap](/docs/ref/std/heap) | O(1) | | `MinMaxHeap.is_empty` | [heap](/docs/ref/std/heap) | O(1) | | `MinMaxHeap.last` | [heap](/docs/ref/std/heap) | O(1) | | `MinMaxHeap.len` | [heap](/docs/ref/std/heap) | O(1) | | `MinMaxHeap.less` | [heap](/docs/ref/std/heap) | | | `MinMaxHeap.max_at` | [heap](/docs/ref/std/heap) | | | `MinMaxHeap.new` | [heap](/docs/ref/std/heap) | O(1) | | `MinMaxHeap.of` | [heap](/docs/ref/std/heap) | O(n) | | `MinMaxHeap.pop_first` | [heap](/docs/ref/std/heap) | O(log n) | | `MinMaxHeap.pop_last` | [heap](/docs/ref/std/heap) | O(log n) | | `MinMaxHeap.push` | [heap](/docs/ref/std/heap) | O(log n), amortized over list growth | | `MinMaxHeap.remove_at` | [heap](/docs/ref/std/heap) | | | `MinMaxHeap.reserve` | [heap](/docs/ref/std/heap) | O(cap) when the storage grows, O(1) otherwise | | `MinMaxHeap.swap` | [heap](/docs/ref/std/heap) | | | `MinMaxHeap.take` | [heap](/docs/ref/std/heap) | O(1) | | `MinMaxHeap.trickle_down` | [heap](/docs/ref/std/heap) | | | `Mod` | [mod](/docs/ref/std/mod) | | | `Mod.from_int` | [mod](/docs/ref/std/mod) | O(1) | | `Mod.inv` | [mod](/docs/ref/std/mod) | O(log P) | | `Mod.inv_all` | [mod](/docs/ref/std/mod) | O(n + log P) | | `Mod.log` | [mod](/docs/ref/std/mod) | O(sqrt P) | | `Mod.new` | [mod](/docs/ref/std/mod) | O(1) | | `Mod.sqrt` | [mod](/docs/ref/std/mod) | O(log^2 P) | | `Mod.try_inv` | [mod](/docs/ref/std/mod) | O(log P) | | `Mod

.add` | [mod](/docs/ref/std/mod) | | | `Mod

.div` | [mod](/docs/ref/std/mod) | | | `Mod

.mul` | [mod](/docs/ref/std/mod) | | | `Mod

.neg` | [mod](/docs/ref/std/mod) | | | `Mod

.pow` | [mod](/docs/ref/std/mod) | | | `Mod

.read` | [mod](/docs/ref/std/mod) | | | `Mod

.show` | [mod](/docs/ref/std/mod) | | | `Mod

.sub` | [mod](/docs/ref/std/mod) | | | `ModComb` | [mod](/docs/ref/std/mod) | | | `ModComb.choose` | [mod](/docs/ref/std/mod) | O(omega(m) log n) | | `ModComb.new` | [mod](/docs/ref/std/mod) | O(sum p_i^e_i) | | `MongePath` | [dp](/docs/ref/std/dp) | | | `MongePath.len` | [dp](/docs/ref/std/dp) | O(1) | | `MongePath.next` | [dp](/docs/ref/std/dp) | O(1) amortized calls of `cost` | | `MongePath.setup` | [dp](/docs/ref/std/dp) | | | `MongePath.val` | [dp](/docs/ref/std/dp) | O(1) | | `MongePath.w` | [dp](/docs/ref/std/dp) | | | `Monoid` | [algebra](/docs/ref/std/algebra) | | | `Monoid.of` | [algebra](/docs/ref/std/algebra) | O(1) | | `MonoStack` | [seq](/docs/ref/std/seq) | | | `MonoStack.clear` | [seq](/docs/ref/std/seq) | O(1) | | `MonoStack.is_empty` | [seq](/docs/ref/std/seq) | O(1) | | `MonoStack.len` | [seq](/docs/ref/std/seq) | O(1) | | `MonoStack.mark` | [seq](/docs/ref/std/seq) | O(1) | | `MonoStack.pops` | [seq](/docs/ref/std/seq) | | | `MonoStack.push` | [seq](/docs/ref/std/seq) | O(1) amortized | | `MonoStack.top` | [seq](/docs/ref/std/seq) | O(1) | | `MonoStack.undo_to` | [seq](/docs/ref/std/seq) | O(1) amortized per undone push | | `MonotoneHull` | [dp](/docs/ref/std/dp) | | | `MonotoneHull.add` | [dp](/docs/ref/std/dp) | O(1) amortized | | `MonotoneHull.at` | [dp](/docs/ref/std/dp) | O(log n) | | `MonotoneHull.at_next` | [dp](/docs/ref/std/dp) | O(1) amortized | | `MonotoneHull.best_next` | [dp](/docs/ref/std/dp) | O(1) amortized | | `MonotoneHull.clear` | [dp](/docs/ref/std/dp) | O(1) | | `MonotoneHull.covered` | [dp](/docs/ref/std/dp) | | | `MonotoneHull.len` | [dp](/docs/ref/std/dp) | O(1) | | `MonotoneHull.pop_line` | [dp](/docs/ref/std/dp) | | | `MonotoneHull.sign` | [dp](/docs/ref/std/dp) | | | `MonotoneHull.val_at` | [dp](/docs/ref/std/dp) | | | `Next` | [graph](/docs/ref/std/graph) | | | `Next.out` | [graph](/docs/ref/std/graph) | O(1) per arc yielded | | `OnlineHull` | [geometry](/docs/ref/std/geometry) | | | `OnlineHull.add` | [geometry](/docs/ref/std/geometry) | O(log n) amortized | | `OnlineHull.area2` | [geometry](/docs/ref/std/geometry) | O(1) | | `OnlineHull.clear` | [geometry](/docs/ref/std/geometry) | O(n) | | `OnlineHull.extreme` | [geometry](/docs/ref/std/geometry) | O(log n) | | `OnlineHull.is_empty` | [geometry](/docs/ref/std/geometry) | O(1) | | `OnlineHull.iter` | [geometry](/docs/ref/std/geometry) | O(n) | | `OnlineHull.len` | [geometry](/docs/ref/std/geometry) | O(1) | | `OnlineHull.locate` | [geometry](/docs/ref/std/geometry) | O(log n) | | `OnlineHull.new` | [geometry](/docs/ref/std/geometry) | O(1) | | `OnlineHull.vertices` | [geometry](/docs/ref/std/geometry) | O(n) time and memory | | `OnlineLis` | [seq](/docs/ref/std/seq) | | | `OnlineLis.clear` | [seq](/docs/ref/std/seq) | O(1) | | `OnlineLis.is_empty` | [seq](/docs/ref/std/seq) | O(1) | | `OnlineLis.len` | [seq](/docs/ref/std/seq) | O(1) | | `OnlineLis.mark` | [seq](/docs/ref/std/seq) | O(1) | | `OnlineLis.push` | [seq](/docs/ref/std/seq) | O(log n) | | `OnlineLis.reconstruct` | [seq](/docs/ref/std/seq) | O(n), O(n) memory | | `OnlineLis.undo_to` | [seq](/docs/ref/std/seq) | O(1) amortized per undone push | | `Only` | [graph](/docs/ref/std/graph) | | | `Only.deg` | [graph](/docs/ref/std/graph) | O(deg u in `g`) | | `Only.out` | [graph](/docs/ref/std/graph) | O(1) to make, O(1) per arc of `g` walked | | `Only.transpose` | [graph](/docs/ref/std/graph) | O(n + m) | | `Op` | [algebra](/docs/ref/std/algebra) | | | `Op.op` | [algebra](/docs/ref/std/algebra) | | | `Ordering` | [algebra](/docs/ref/std/algebra) | | | `Pair` | [pair](/docs/ref/std/pair) | | | `Pair.at` | [pair](/docs/ref/std/pair) | O(1) | | `Pair.new` | [pair](/docs/ref/std/pair) | O(1) | | `Pair.other` | [pair](/docs/ref/std/pair) | O(1) | | `Palindromes` | [strings](/docs/ref/std/strings) | | | `Palindromes.count` | [strings](/docs/ref/std/strings) | O(n) | | `Palindromes.is_empty` | [strings](/docs/ref/std/strings) | O(1) | | `Palindromes.is_palindrome` | [strings](/docs/ref/std/strings) | O(1) | | `Palindromes.len` | [strings](/docs/ref/std/strings) | O(1) | | `Palindromes.longest` | [strings](/docs/ref/std/strings) | O(n) | | `Palindromes.longest_at` | [strings](/docs/ref/std/strings) | | | `Palindromes.longest_between` | [strings](/docs/ref/std/strings) | | | `PalindromicTree` | [strings](/docs/ref/std/strings) | | | `PalindromicTree.at` | [strings](/docs/ref/std/strings) | | | `PalindromicTree.contains` | [strings](/docs/ref/std/strings) | O(\|word\|) | | `PalindromicTree.diff` | [strings](/docs/ref/std/strings) | | | `PalindromicTree.distinct` | [strings](/docs/ref/std/strings) | O(1) | | `PalindromicTree.grow` | [strings](/docs/ref/std/strings) | | | `PalindromicTree.last_state` | [strings](/docs/ref/std/strings) | O(1) | | `PalindromicTree.len` | [strings](/docs/ref/std/strings) | O(1) | | `PalindromicTree.link` | [strings](/docs/ref/std/strings) | | | `PalindromicTree.min_palindrome_partition` | [strings](/docs/ref/std/strings) | O(n log n) | | `PalindromicTree.new` | [strings](/docs/ref/std/strings) | O(\|A\|) | | `PalindromicTree.occ_counts` | [strings](/docs/ref/std/strings) | | | `PalindromicTree.of` | [strings](/docs/ref/std/strings) | O(\|s\| * \|A\|) memory, O(\|s\|) amortized time | | `PalindromicTree.pal_len` | [strings](/docs/ref/std/strings) | | | `PalindromicTree.pop` | [strings](/docs/ref/std/strings) | O(1) amortized | | `PalindromicTree.push` | [strings](/docs/ref/std/strings) | | | `PalindromicTree.push_front` | [strings](/docs/ref/std/strings) | O(1) amortized | | `PalindromicTree.series_link` | [strings](/docs/ref/std/strings) | | | `PalindromicTree.size` | [strings](/docs/ref/std/strings) | | | `PalindromicTree.step` | [strings](/docs/ref/std/strings) | | | `ParityDsu` | [dsu](/docs/ref/std/dsu) | | | `ParityDsu.consistent` | [dsu](/docs/ref/std/dsu) | O(1) | | `ParityDsu.diff` | [dsu](/docs/ref/std/dsu) | O(log n) | | `ParityDsu.find` | [dsu](/docs/ref/std/dsu) | O(log n) | | `ParityDsu.mark` | [dsu](/docs/ref/std/dsu) | O(1) | | `ParityDsu.new` | [dsu](/docs/ref/std/dsu) | O(n); three `[V]` arrays | | `ParityDsu.same` | [dsu](/docs/ref/std/dsu) | O(log n) | | `ParityDsu.size` | [dsu](/docs/ref/std/dsu) | O(log n) | | `ParityDsu.undo_to` | [dsu](/docs/ref/std/dsu) | O(1) per undone `unite` | | `ParityDsu.unite` | [dsu](/docs/ref/std/dsu) | O(log n), plus one log entry when it merges or contradicts | | `ParityDsu.mark` | [window](/docs/ref/std/window) | | | `ParityDsu.undo_to` | [window](/docs/ref/std/window) | | | `Paths` | [graph](/docs/ref/std/graph) | | | `Paths.arcs` | [graph](/docs/ref/std/graph) | O(path length) | | `Paths.get` | [graph](/docs/ref/std/graph) | O(1) dense, O(1) expected `hashed` | | `Paths.iter` | [graph](/docs/ref/std/graph) | O(1) to make, O(1) per item | | `Paths.path` | [graph](/docs/ref/std/graph) | O(path length) | | `Paths.reached` | [graph](/docs/ref/std/graph) | O(1) | | `Paths.tight` | [graph](/docs/ref/std/graph) | O(n + m) | | `PermKind` | [tree](/docs/ref/std/tree) | | | `PermNode` | [tree](/docs/ref/std/tree) | | | `PermTree` | [tree](/docs/ref/std/tree) | | | `PermTree.leaf` | [tree](/docs/ref/std/tree) | O(1) | | `PermTree.left` | [tree](/docs/ref/std/tree) | O(1) | | `PermTree.new` | [tree](/docs/ref/std/tree) | O(n) | | `PermTree.node` | [tree](/docs/ref/std/tree) | O(1) | | `PermTree.right` | [tree](/docs/ref/std/tree) | O(1) | | `PermTree.span` | [tree](/docs/ref/std/tree) | O(1) | | `PermTree.vals` | [tree](/docs/ref/std/tree) | O(1) | | `PersistentArray` | [persistent](/docs/ref/std/persistent) | | | `PersistentArray.base` | [persistent](/docs/ref/std/persistent) | O(1) | | `PersistentArray.build_list` | [persistent](/docs/ref/std/persistent) | | | `PersistentArray.get` | [persistent](/docs/ref/std/persistent) | O(log n) | | `PersistentArray.new` | [persistent](/docs/ref/std/persistent) | O(n) time and memory for n = `\|D\|` | | `PersistentArray.push_node` | [persistent](/docs/ref/std/persistent) | | | `PersistentArray.set` | [persistent](/docs/ref/std/persistent) | O(log n) time and memory | | `PersistentArray.set_rec` | [persistent](/docs/ref/std/persistent) | | | `PersistentDsu` | [dsu](/docs/ref/std/dsu) | | | `PersistentDsu.base` | [dsu](/docs/ref/std/dsu) | O(1) | | `PersistentDsu.build` | [dsu](/docs/ref/std/dsu) | | | `PersistentDsu.find` | [dsu](/docs/ref/std/dsu) | O(log² n) | | `PersistentDsu.get` | [dsu](/docs/ref/std/dsu) | | | `PersistentDsu.new` | [dsu](/docs/ref/std/dsu) | O(n) | | `PersistentDsu.put` | [dsu](/docs/ref/std/dsu) | | | `PersistentDsu.reserve` | [dsu](/docs/ref/std/dsu) | O(nodes) | | `PersistentDsu.root_ord` | [dsu](/docs/ref/std/dsu) | | | `PersistentDsu.same` | [dsu](/docs/ref/std/dsu) | O(log² n) | | `PersistentDsu.size` | [dsu](/docs/ref/std/dsu) | O(log² n) | | `PersistentDsu.unite` | [dsu](/docs/ref/std/dsu) | O(log² n) time and O(log n) memory | | `PersistentLazySegTree` | [persistent](/docs/ref/std/persistent) | | | `PersistentLazySegTree.all` | [persistent](/docs/ref/std/persistent) | O(1) | | `PersistentLazySegTree.apply` | [persistent](/docs/ref/std/persistent) | O(log n) time and memory | | `PersistentLazySegTree.apply_rec` | [persistent](/docs/ref/std/persistent) | | | `PersistentLazySegTree.base` | [persistent](/docs/ref/std/persistent) | O(1) | | `PersistentLazySegTree.build_list` | [persistent](/docs/ref/std/persistent) | | | `PersistentLazySegTree.fold` | [persistent](/docs/ref/std/persistent) | O(log n) | | `PersistentLazySegTree.fold_rec` | [persistent](/docs/ref/std/persistent) | | | `PersistentLazySegTree.get` | [persistent](/docs/ref/std/persistent) | O(log n) | | `PersistentLazySegTree.new` | [persistent](/docs/ref/std/persistent) | O(n) time and memory with `a:` or `fill:`, O(1) otherwise, for n = `\|D\|` | | `PersistentLazySegTree.push_node` | [persistent](/docs/ref/std/persistent) | | | `PersistentLazySegTree.set` | [persistent](/docs/ref/std/persistent) | O(log n) time and memory | | `PersistentLazySegTree.set_rec` | [persistent](/docs/ref/std/persistent) | | | `PersistentLazySegTree.tagged` | [persistent](/docs/ref/std/persistent) | | | `PersistentSegTree` | [persistent](/docs/ref/std/persistent) | | | `PersistentSegTree.all` | [persistent](/docs/ref/std/persistent) | O(1) | | `PersistentSegTree.base` | [persistent](/docs/ref/std/persistent) | O(1) | | `PersistentSegTree.build_list` | [persistent](/docs/ref/std/persistent) | | | `PersistentSegTree.diff_kth` | [persistent](/docs/ref/std/persistent) | O(log n) | | `PersistentSegTree.fold` | [persistent](/docs/ref/std/persistent) | O(log n) | | `PersistentSegTree.fold_rec` | [persistent](/docs/ref/std/persistent) | | | `PersistentSegTree.get` | [persistent](/docs/ref/std/persistent) | O(log n) | | `PersistentSegTree.left_while` | [persistent](/docs/ref/std/persistent) | O(log n) calls of `ok` | | `PersistentSegTree.lw` | [persistent](/docs/ref/std/persistent) | | | `PersistentSegTree.new` | [persistent](/docs/ref/std/persistent) | O(n) time and memory with `a:` or `fill:`, O(1) otherwise, for n = `\|D\|` | | `PersistentSegTree.push_node` | [persistent](/docs/ref/std/persistent) | | | `PersistentSegTree.reserve` | [persistent](/docs/ref/std/persistent) | O(nodes) | | `PersistentSegTree.right_while` | [persistent](/docs/ref/std/persistent) | O(log n) calls of `ok` | | `PersistentSegTree.rw` | [persistent](/docs/ref/std/persistent) | | | `PersistentSegTree.set` | [persistent](/docs/ref/std/persistent) | O(log n) time and memory | | `PersistentSegTree.set_rec` | [persistent](/docs/ref/std/persistent) | | | `PersistentSegTree.update` | [persistent](/docs/ref/std/persistent) | O(log n) time and memory, one call of `f` | | `PersistentSegTree.update_rec` | [persistent](/docs/ref/std/persistent) | | | `Plane3` | [geometry](/docs/ref/std/geometry) | | | `Plane3.dist` | [geometry](/docs/ref/std/geometry) | O(1) | | `Plane3.project` | [geometry](/docs/ref/std/geometry) | O(1) | | `Plane3.through` | [geometry](/docs/ref/std/geometry) | O(1) | | `PMultiset` | [persistent](/docs/ref/std/persistent) | | | `PMultiset.cmp` | [persistent](/docs/ref/std/persistent) | O(log \|D\|) | | `PMultiset.count` | [persistent](/docs/ref/std/persistent) | O(log \|D\|) | | `PMultiset.empty` | [persistent](/docs/ref/std/persistent) | O(1) | | `PMultiset.with` | [persistent](/docs/ref/std/persistent) | O(log \|D\|) time and memory | | `PMultiset.without` | [persistent](/docs/ref/std/persistent) | O(log \|D\|) time and memory | | `Poly` | [poly](/docs/ref/std/poly) | | | `Poly.at` | [poly](/docs/ref/std/poly) | O(1) | | `Poly.deg` | [poly](/docs/ref/std/poly) | O(1) plus the number of stored trailing zeros | | `Poly.deriv` | [poly](/docs/ref/std/poly) | O(n) | | `Poly.eval` | [poly](/docs/ref/std/poly) | O(n) | | `Poly.exp` | [poly](/docs/ref/std/poly) | O(n log n) | | `Poly.from_int` | [poly](/docs/ref/std/poly) | O(1) | | `Poly.integral` | [poly](/docs/ref/std/poly) | O(n) | | `Poly.inv` | [poly](/docs/ref/std/poly) | O(n log n) | | `Poly.is_zero` | [poly](/docs/ref/std/poly) | O(1) plus the number of stored trailing zeros | | `Poly.len` | [poly](/docs/ref/std/poly) | O(1) | | `Poly.log` | [poly](/docs/ref/std/poly) | O(n log n) | | `Poly.new` | [poly](/docs/ref/std/poly) | O(n) | | `Poly.one` | [poly](/docs/ref/std/poly) | O(1) | | `Poly.pow` | [poly](/docs/ref/std/poly) | O(n log n) | | `Poly.set` | [poly](/docs/ref/std/poly) | O(1), or O(i) when it grows | | `Poly.shift` | [poly](/docs/ref/std/poly) | O(n log n) | | `Poly.sqrt` | [poly](/docs/ref/std/poly) | O(n log n + log^2 P) | | `Poly.transposed_mul` | [poly](/docs/ref/std/poly) | O((n + m) log(n + m)) | | `Poly.truncated` | [poly](/docs/ref/std/poly) | O(n) | | `Poly.x` | [poly](/docs/ref/std/poly) | O(1) | | `Poly.zero` | [poly](/docs/ref/std/poly) | O(1) | | `Poly.add` | [poly](/docs/ref/std/poly) | | | `Poly.div` | [poly](/docs/ref/std/poly) | | | `Poly.mul` | [poly](/docs/ref/std/poly) | | | `Poly.neg` | [poly](/docs/ref/std/poly) | | | `Poly.sub` | [poly](/docs/ref/std/poly) | | | `PotentialDsu` | [dsu](/docs/ref/std/dsu) | | | `PotentialDsu.components` | [dsu](/docs/ref/std/dsu) | O(1) | | `PotentialDsu.consistent` | [dsu](/docs/ref/std/dsu) | O(1) | | `PotentialDsu.diff` | [dsu](/docs/ref/std/dsu) | O(log n) | | `PotentialDsu.find` | [dsu](/docs/ref/std/dsu) | O(log n) | | `PotentialDsu.mark` | [dsu](/docs/ref/std/dsu) | O(1) | | `PotentialDsu.new` | [dsu](/docs/ref/std/dsu) | O(n); three `[V]` arrays | | `PotentialDsu.same` | [dsu](/docs/ref/std/dsu) | O(log n) | | `PotentialDsu.size` | [dsu](/docs/ref/std/dsu) | O(log n) | | `PotentialDsu.undo_to` | [dsu](/docs/ref/std/dsu) | O(1) per undone `unite` | | `PotentialDsu.unite` | [dsu](/docs/ref/std/dsu) | O(log n), plus one log entry when it merges or contradicts | | `PotentialDsu.mark` | [window](/docs/ref/std/window) | | | `PotentialDsu.undo_to` | [window](/docs/ref/std/window) | | | `PreferredPaths` | [tree](/docs/ref/std/tree) | | | `PreferredPaths.access` | [tree](/docs/ref/std/tree) | amortized O(log n) switches | | `PreferredPaths.new` | [tree](/docs/ref/std/tree) | O(n) | | `Prefix` | [prefix](/docs/ref/std/prefix) | | | `Prefix.all` | [prefix](/docs/ref/std/prefix) | O(1) | | `Prefix.cyclic_sum` | [prefix](/docs/ref/std/prefix) | O(1) | | `Prefix.filling` | [prefix](/docs/ref/std/prefix) | O(\|D\|) time and space | | `Prefix.first_ge` | [prefix](/docs/ref/std/prefix) | O(log \|D\|) | | `Prefix.first_gt` | [prefix](/docs/ref/std/prefix) | O(log \|D\|) | | `Prefix.fold` | [prefix](/docs/ref/std/prefix) | O(1) | | `Prefix.get` | [prefix](/docs/ref/std/prefix) | O(1) | | `Prefix.new` | [prefix](/docs/ref/std/prefix) | O(\|D\|) time and space | | `Prefix.of_cuts` | [prefix](/docs/ref/std/prefix) | | | `Prefix.prefix` | [prefix](/docs/ref/std/prefix) | O(1) | | `Prefix.suffix` | [prefix](/docs/ref/std/prefix) | O(1) | | `PrefixXorBasis` | [matrix](/docs/ref/std/matrix) | | | `PrefixXorBasis.contains` | [matrix](/docs/ref/std/matrix) | O(62) | | `PrefixXorBasis.max_xor` | [matrix](/docs/ref/std/matrix) | O(62) | | `PrefixXorBasis.new` | [matrix](/docs/ref/std/matrix) | O(1) | | `PrefixXorBasis.push` | [matrix](/docs/ref/std/matrix) | O(62) time and space | | `PrefixXorBasis.rank` | [matrix](/docs/ref/std/matrix) | O(62) | | `PrimePowerComb` | [mod](/docs/ref/std/mod) | | | `PrimePowerComb.choose` | [mod](/docs/ref/std/mod) | O(log_p n) | | `PrimePowerComb.free_fact` | [mod](/docs/ref/std/mod) | | | `PrimePowerComb.new` | [mod](/docs/ref/std/mod) | O(p^e) time and memory | | `PrimePowerComb.p_count` | [mod](/docs/ref/std/mod) | | | `Pt` | [geometry](/docs/ref/std/geometry) | | | `Pt.add` | [geometry](/docs/ref/std/geometry) | | | `Pt.angle` | [geometry](/docs/ref/std/geometry) | O(1) | | `Pt.chebyshev` | [geometry](/docs/ref/std/geometry) | O(1) | | `Pt.cross` | [geometry](/docs/ref/std/geometry) | O(1) | | `Pt.cross128` | [geometry](/docs/ref/std/geometry) | O(1) | | `Pt.dist` | [geometry](/docs/ref/std/geometry) | O(1) | | `Pt.dist2` | [geometry](/docs/ref/std/geometry) | O(1) | | `Pt.dist2_128` | [geometry](/docs/ref/std/geometry) | O(1) | | `Pt.dot` | [geometry](/docs/ref/std/geometry) | O(1) | | `Pt.dot128` | [geometry](/docs/ref/std/geometry) | O(1) | | `Pt.len` | [geometry](/docs/ref/std/geometry) | O(1) | | `Pt.manhattan` | [geometry](/docs/ref/std/geometry) | O(1) | | `Pt.mul` | [geometry](/docs/ref/std/geometry) | | | `Pt.neg` | [geometry](/docs/ref/std/geometry) | | | `Pt.norm2` | [geometry](/docs/ref/std/geometry) | O(1) | | `Pt.norm2_128` | [geometry](/docs/ref/std/geometry) | O(1) | | `Pt.perp` | [geometry](/docs/ref/std/geometry) | O(1) | | `Pt.perp_cw` | [geometry](/docs/ref/std/geometry) | O(1) | | `Pt.show` | [geometry](/docs/ref/std/geometry) | | | `Pt.sub` | [geometry](/docs/ref/std/geometry) | | | `Pt.to_vec` | [geometry](/docs/ref/std/geometry) | O(1) | | `Pt.unit_dir` | [geometry](/docs/ref/std/geometry) | O(log max(\|x\|, \|y\|)) | | `Pt3` | [geometry](/docs/ref/std/geometry) | | | `Pt3.add` | [geometry](/docs/ref/std/geometry) | | | `Pt3.chebyshev` | [geometry](/docs/ref/std/geometry) | O(1) | | `Pt3.cross` | [geometry](/docs/ref/std/geometry) | O(1) | | `Pt3.dist` | [geometry](/docs/ref/std/geometry) | O(1) | | `Pt3.dist2` | [geometry](/docs/ref/std/geometry) | O(1) | | `Pt3.dot` | [geometry](/docs/ref/std/geometry) | O(1) | | `Pt3.dot128` | [geometry](/docs/ref/std/geometry) | O(1) | | `Pt3.len` | [geometry](/docs/ref/std/geometry) | O(1) | | `Pt3.manhattan` | [geometry](/docs/ref/std/geometry) | O(1) | | `Pt3.mul` | [geometry](/docs/ref/std/geometry) | | | `Pt3.neg` | [geometry](/docs/ref/std/geometry) | | | `Pt3.norm2` | [geometry](/docs/ref/std/geometry) | O(1) | | `Pt3.norm2_128` | [geometry](/docs/ref/std/geometry) | O(1) | | `Pt3.show` | [geometry](/docs/ref/std/geometry) | | | `Pt3.sub` | [geometry](/docs/ref/std/geometry) | | | `Pt3.to_vec3` | [geometry](/docs/ref/std/geometry) | O(1) | | `RangeKth` | [persistent](/docs/ref/std/persistent) | | | `RangeKth.count_in` | [persistent](/docs/ref/std/persistent) | O(log n) | | `RangeKth.count_le` | [persistent](/docs/ref/std/persistent) | O(log n) | | `RangeKth.count_lt` | [persistent](/docs/ref/std/persistent) | O(log n) | | `RangeKth.count_prefix` | [persistent](/docs/ref/std/persistent) | | | `RangeKth.inc` | [persistent](/docs/ref/std/persistent) | | | `RangeKth.kth` | [persistent](/docs/ref/std/persistent) | O(log n) | | `RangeKth.lower_val` | [persistent](/docs/ref/std/persistent) | | | `RangeKth.new` | [persistent](/docs/ref/std/persistent) | O(n log n) time and memory for n = `a.len` | | `RangeKth.upper_val` | [persistent](/docs/ref/std/persistent) | | | `Ratio` | [math](/docs/ref/std/math) | | | `Ratio.abs` | [math](/docs/ref/std/math) | O(1) | | `Ratio.add` | [math](/docs/ref/std/math) | | | `Ratio.ceil` | [math](/docs/ref/std/math) | O(1) | | `Ratio.div` | [math](/docs/ref/std/math) | | | `Ratio.floor` | [math](/docs/ref/std/math) | O(1) | | `Ratio.from_int` | [math](/docs/ref/std/math) | O(1) | | `Ratio.inv` | [math](/docs/ref/std/math) | O(1) | | `Ratio.lt` | [math](/docs/ref/std/math) | | | `Ratio.mul` | [math](/docs/ref/std/math) | | | `Ratio.neg` | [math](/docs/ref/std/math) | | | `Ratio.new` | [math](/docs/ref/std/math) | O(log min(\|p\|, \|q\|)) | | `Ratio.show` | [math](/docs/ref/std/math) | | | `Ratio.sub` | [math](/docs/ref/std/math) | | | `Rebased` | [seq](/docs/ref/std/seq) | | | `Rect` | [geometry](/docs/ref/std/geometry) | | | `Rect.area` | [geometry](/docs/ref/std/geometry) | O(1) | | `Rect.contains` | [geometry](/docs/ref/std/geometry) | O(1) | | `Rect.intersect` | [geometry](/docs/ref/std/geometry) | O(1) | | `Rect.is_empty` | [geometry](/docs/ref/std/geometry) | O(1) | | `RelaxedConvolve` | [ntt](/docs/ref/std/ntt) | | | `RelaxedConvolve.new` | [ntt](/docs/ref/std/ntt) | O(1) | | `RelaxedConvolve.push` | [ntt](/docs/ref/std/ntt) | O(log^2 k) amortized | | `Rev` | [seq](/docs/ref/std/seq) | | | `Rev.src` | [seq](/docs/ref/std/seq) | O(1) | | `Reversible` | [algebra](/docs/ref/std/algebra) | | | `Reversible.rev` | [algebra](/docs/ref/std/algebra) | | | `Reweighted` | [graph](/docs/ref/std/graph) | | | `Ring` | [seq](/docs/ref/std/seq) | | | `Ring.from` | [seq](/docs/ref/std/seq) | O(1) per step | | `Ring.maximal` | [seq](/docs/ref/std/seq) | O(n) pushes and pops on `state` | | `Ring.minimal` | [seq](/docs/ref/std/seq) | O(n) pushes and pops on `state` | | `Ring.next` | [seq](/docs/ref/std/seq) | O(1) | | `Ring.prev` | [seq](/docs/ref/std/seq) | O(1) | | `Ring.span` | [seq](/docs/ref/std/seq) | O(1) | | `Ring.step` | [seq](/docs/ref/std/seq) | O(1) | | `Ring.windows` | [seq](/docs/ref/std/seq) | O(1) per window | | `RingRange` | [seq](/docs/ref/std/seq) | | | `RingRange.contains` | [seq](/docs/ref/std/seq) | O(1) | | `RingRange.end` | [seq](/docs/ref/std/seq) | O(1) | | `RingRange.keys` | [seq](/docs/ref/std/seq) | O(1) to make, O(1) per step | | `RingRange.len` | [seq](/docs/ref/std/seq) | O(1) | | `RingRange.start` | [seq](/docs/ref/std/seq) | O(1) | | `RingSlice` | [seq](/docs/ref/std/seq) | | | `RingSlice.end` | [seq](/docs/ref/std/seq) | O(1) | | `RingSlice.keys` | [seq](/docs/ref/std/seq) | O(1) to make, O(1) per step | | `RingSlice.len` | [seq](/docs/ref/std/seq) | O(1) | | `RingSlice.range` | [seq](/docs/ref/std/seq) | O(1) | | `RingSlice.start` | [seq](/docs/ref/std/seq) | O(1) | | `Rng` | [rand](/docs/ref/std/rand) | | | `Rng.chance` | [rand](/docs/ref/std/rand) | O(1) | | `Rng.float` | [rand](/docs/ref/std/rand) | O(1) | | `Rng.int` | [rand](/docs/ref/std/rand) | O(1) | | `Rng.new` | [rand](/docs/ref/std/rand) | O(1) | | `Rng.next` | [rand](/docs/ref/std/rand) | O(1) | | `Rng.perm` | [rand](/docs/ref/std/rand) | O(n) | | `Rng.pick` | [rand](/docs/ref/std/rand) | O(1) | | `Rng.sample` | [rand](/docs/ref/std/rand) | O(\|from\|) | | `Rng.shuffle` | [rand](/docs/ref/std/rand) | O(n) | | `RollbackArray` | [dsu](/docs/ref/std/dsu) | | | `RollbackArray.get` | [dsu](/docs/ref/std/dsu) | O(1) | | `RollbackArray.mark` | [dsu](/docs/ref/std/dsu) | O(1) | | `RollbackArray.new` | [dsu](/docs/ref/std/dsu) | O(n) calls of `init`, for n = `D.count` | | `RollbackArray.set` | [dsu](/docs/ref/std/dsu) | O(1), plus one log entry | | `RollbackArray.undo_to` | [dsu](/docs/ref/std/dsu) | O(1) per undone `set` | | `RollingHash` | [strings](/docs/ref/std/strings) | | | `RollingHash.all` | [strings](/docs/ref/std/strings) | O(1) | | `RollingHash.combine` | [strings](/docs/ref/std/strings) | O(1) amortized (the power table grows past `len` on demand) | | `RollingHash.concat` | [strings](/docs/ref/std/strings) | O(\|parts\|) amortized | | `RollingHash.eq_sub` | [strings](/docs/ref/std/strings) | | | `RollingHash.get` | [strings](/docs/ref/std/strings) | O(1) | | `RollingHash.hash_of` | [strings](/docs/ref/std/strings) | O(\|seq\|) | | `RollingHash.is_empty` | [strings](/docs/ref/std/strings) | O(1) | | `RollingHash.lcp` | [strings](/docs/ref/std/strings) | O(log n) | | `RollingHash.lcp_with` | [strings](/docs/ref/std/strings) | O(log min(\|self\| - a, \|other\| - b)) | | `RollingHash.lcs` | [strings](/docs/ref/std/strings) | O(log n) | | `RollingHash.len` | [strings](/docs/ref/std/strings) | O(1) | | `RollingHash.new` | [strings](/docs/ref/std/strings) | | | `RollingHash.pop` | [strings](/docs/ref/std/strings) | O(1) | | `RollingHash.push` | [strings](/docs/ref/std/strings) | O(1) amortized | | `RollingHash.raw_slice` | [strings](/docs/ref/std/strings) | | | `RollingHash.slice` | [strings](/docs/ref/std/strings) | O(1) | | `RollingHash61` | [strings](/docs/ref/std/strings) | | | `RollingHash61.all` | [strings](/docs/ref/std/strings) | O(1) | | `RollingHash61.combine` | [strings](/docs/ref/std/strings) | O(1) amortized (the power table grows past `len` on demand) | | `RollingHash61.get` | [strings](/docs/ref/std/strings) | O(1) | | `RollingHash61.is_empty` | [strings](/docs/ref/std/strings) | O(1) | | `RollingHash61.lcp` | [strings](/docs/ref/std/strings) | O(log n) | | `RollingHash61.lcp_with` | [strings](/docs/ref/std/strings) | O(log min(\|self\| - a, \|other\| - b)) | | `RollingHash61.lcs` | [strings](/docs/ref/std/strings) | O(log n) | | `RollingHash61.len` | [strings](/docs/ref/std/strings) | O(1) | | `RollingHash61.new` | [strings](/docs/ref/std/strings) | O(n) | | `RollingHash61.pop` | [strings](/docs/ref/std/strings) | O(1) | | `RollingHash61.push` | [strings](/docs/ref/std/strings) | O(1) amortized | | `RollingHash61.slice61` | [strings](/docs/ref/std/strings) | | | `Rooted` | [tree](/docs/ref/std/tree) | | | `Rooted.above` | [tree](/docs/ref/std/tree) | O(n) calls of `lift` and `finish`, O(n) calls of `op` | | `Rooted.ancestor` | [tree](/docs/ref/std/tree) | O(log n) | | `Rooted.ancestors` | [tree](/docs/ref/std/tree) | O(1) per vertex, O(depth(v)) in all | | `Rooted.apply_path` | [tree](/docs/ref/std/tree) | O(log² n) | | `Rooted.below` | [tree](/docs/ref/std/tree) | O(1) | | `Rooted.build` | [tree](/docs/ref/std/tree) | | | `Rooted.centroid` | [tree](/docs/ref/std/tree) | O(depth) | | `Rooted.centroids` | [tree](/docs/ref/std/tree) | O(depth) | | `Rooted.chain` | [tree](/docs/ref/std/tree) | O(1) | | `Rooted.chains` | [tree](/docs/ref/std/tree) | O(log n) ranges | | `Rooted.child_arcs` | [tree](/docs/ref/std/tree) | O(1) per child | | `Rooted.children` | [tree](/docs/ref/std/tree) | O(1) to start, O(1) per child | | `Rooted.depth` | [tree](/docs/ref/std/tree) | O(1) | | `Rooted.diameter` | [tree](/docs/ref/std/tree) | O(n) | | `Rooted.dist` | [tree](/docs/ref/std/tree) | O(log n) | | `Rooted.down` | [tree](/docs/ref/std/tree) | O(n) calls of `f` | | `Rooted.euler_tour` | [tree](/docs/ref/std/tree) | O(1) per item | | `Rooted.events` | [tree](/docs/ref/std/tree) | O(n) | | `Rooted.excl_fold` | [tree](/docs/ref/std/tree) | O(k) calls of `f` and of `op`, O(k) memory | | `Rooted.farthest` | [tree](/docs/ref/std/tree) | O(log n): at most four `dist` calls | | `Rooted.fold_path` | [tree](/docs/ref/std/tree) | O(log² n) with one structure | | `Rooted.forest` | [tree](/docs/ref/std/tree) | O(n + m) | | `Rooted.from_parents` | [tree](/docs/ref/std/tree) | O(n) | | `Rooted.is_anc` | [tree](/docs/ref/std/tree) | O(1) | | `Rooted.jump` | [tree](/docs/ref/std/tree) | O(log n) | | `Rooted.jump_while` | [tree](/docs/ref/std/tree) | O(log² n) calls of `pred` | | `Rooted.layers` | [tree](/docs/ref/std/tree) | O(n) | | `Rooted.lca` | [tree](/docs/ref/std/tree) | O(log n) | | `Rooted.light` | [tree](/docs/ref/std/tree) | O(children) | | `Rooted.long_paths` | [tree](/docs/ref/std/tree) | O(n) | | `Rooted.lower` | [tree](/docs/ref/std/tree) | O(1) | | `Rooted.meet` | [tree](/docs/ref/std/tree) | O(log n) | | `Rooted.new` | [tree](/docs/ref/std/tree) | O(n + m) for m listed arcs, without recursion | | `Rooted.on_path` | [tree](/docs/ref/std/tree) | O(log n) | | `Rooted.parent` | [tree](/docs/ref/std/tree) | O(1) | | `Rooted.path` | [tree](/docs/ref/std/tree) | O(log n + \|path\|) | | `Rooted.pos` | [tree](/docs/ref/std/tree) | O(1) | | `Rooted.preorder` | [tree](/docs/ref/std/tree) | O(size(v)), less when pruned | | `Rooted.reorder` | [tree](/docs/ref/std/tree) | O(n) | | `Rooted.reroot` | [tree](/docs/ref/std/tree) | O(n) calls of `lift` and `finish`, O(n) calls of `op` | | `Rooted.root_of` | [tree](/docs/ref/std/tree) | O(log n) | | `Rooted.roots` | [tree](/docs/ref/std/tree) | O(1) to make, O(1) per root | | `Rooted.shapes` | [tree](/docs/ref/std/tree) | O(n log n) | | `Rooted.size` | [tree](/docs/ref/std/tree) | O(1) | | `Rooted.sub` | [tree](/docs/ref/std/tree) | O(1) | | `Rooted.sub_at` | [tree](/docs/ref/std/tree) | O(log n) | | `Rooted.subtree` | [tree](/docs/ref/std/tree) | O(size(v)) | | `Rooted.subtree_sizes` | [tree](/docs/ref/std/tree) | O(1); a view of the stored sizes | | `Rooted.top` | [tree](/docs/ref/std/tree) | O(1) | | `Rooted.tour` | [tree](/docs/ref/std/tree) | O(1) to make, O(n) to walk | | `Rooted.try_from_parents` | [tree](/docs/ref/std/tree) | O(n) | | `Rooted.up` | [tree](/docs/ref/std/tree) | O(n) calls of `lift`, `op` and `finish` | | `Rooted.up_arc` | [tree](/docs/ref/std/tree) | O(1) | | `Rooted.virtual` | [tree](/docs/ref/std/tree) | O(k log k + k log n) for k keys | | `Rooted.w` | [tree](/docs/ref/std/tree) | O(1) | | `Rope` | [lazy](/docs/ref/std/lazy) | | | `Rope.apply` | [lazy](/docs/ref/std/lazy) | O(log n) expected | | `Rope.down` | [lazy](/docs/ref/std/lazy) | | | `Rope.emit` | [lazy](/docs/ref/std/lazy) | | | `Rope.find` | [lazy](/docs/ref/std/lazy) | | | `Rope.get` | [lazy](/docs/ref/std/lazy) | O(log n) expected | | `Rope.join` | [lazy](/docs/ref/std/lazy) | | | `Rope.new` | [lazy](/docs/ref/std/lazy) | O(\|D\|) | | `Rope.pull` | [lazy](/docs/ref/std/lazy) | | | `Rope.reverse` | [lazy](/docs/ref/std/lazy) | O(log n) expected | | `Rope.set` | [lazy](/docs/ref/std/lazy) | O(log n) expected | | `Rope.size` | [lazy](/docs/ref/std/lazy) | | | `Rope.split` | [lazy](/docs/ref/std/lazy) | | | `Rope.tag_node` | [lazy](/docs/ref/std/lazy) | | | `Rope.to_array` | [lazy](/docs/ref/std/lazy) | O(\|D\|) | | `SegTree` | [segtree](/docs/ref/std/segtree) | | | `SegTree.all` | [segtree](/docs/ref/std/segtree) | O(1) | | `SegTree.apply` | [segtree](/docs/ref/std/segtree) | O(log \|D\|) | | `SegTree.apply_all` | [segtree](/docs/ref/std/segtree) | O(1) amortized when the tags commute, else O(\|D\|) | | `SegTree.at` | [segtree](/docs/ref/std/segtree) | O(log \|D\|) per write | | `SegTree.build` | [segtree](/docs/ref/std/segtree) | | | `SegTree.build_lazy` | [segtree](/docs/ref/std/segtree) | | | `SegTree.clear` | [segtree](/docs/ref/std/segtree) | O(\|D\|) | | `SegTree.fold` | [segtree](/docs/ref/std/segtree) | O(log \|D\|) | | `SegTree.get` | [segtree](/docs/ref/std/segtree) | O(1); O(log \|D\|) on a tree with `act:` | | `SegTree.left_while` | [segtree](/docs/ref/std/segtree) | O(log \|D\|) | | `SegTree.monoid` | [segtree](/docs/ref/std/segtree) | O(1) | | `SegTree.new` | [segtree](/docs/ref/std/segtree) | O(\|D\|); O(1) with `over:` | | `SegTree.of` | [segtree](/docs/ref/std/segtree) | O(\|D\|), calling `f` once per position in key order | | `SegTree.open` | [segtree](/docs/ref/std/segtree) | | | `SegTree.pull` | [segtree](/docs/ref/std/segtree) | | | `SegTree.pull_node` | [segtree](/docs/ref/std/segtree) | | | `SegTree.push` | [segtree](/docs/ref/std/segtree) | | | `SegTree.put` | [segtree](/docs/ref/std/segtree) | | | `SegTree.refresh` | [segtree](/docs/ref/std/segtree) | O(log \|D\|) plus one call of `f` | | `SegTree.right_while` | [segtree](/docs/ref/std/segtree) | O(log \|D\|) | | `SegTree.set` | [segtree](/docs/ref/std/segtree) | O(log \|D\|) | | `SegTree.try_fold` | [segtree](/docs/ref/std/segtree) | O(log \|D\|) | | `SegTree.update` | [segtree](/docs/ref/std/segtree) | O(log \|D\|) plus one call of `f` | | `SegTree.walk` | [segtree](/docs/ref/std/segtree) | O(log \|D\|) | | `SegTree2D` | [segtree](/docs/ref/std/segtree) | | | `SegTree2D.all` | [segtree](/docs/ref/std/segtree) | O(1) | | `SegTree2D.fold` | [segtree](/docs/ref/std/segtree) | O(log \|R\| * log \|C\|) | | `SegTree2D.fold_row` | [segtree](/docs/ref/std/segtree) | | | `SegTree2D.get` | [segtree](/docs/ref/std/segtree) | O(1) | | `SegTree2D.new` | [segtree](/docs/ref/std/segtree) | O(\|R\| * \|C\|) | | `SegTree2D.set` | [segtree](/docs/ref/std/segtree) | O(log \|R\| * log \|C\|) | | `SegTree2D.update` | [segtree](/docs/ref/std/segtree) | O(log \|R\| * log \|C\|) plus one call of `f` | | `Selective` | [algebra](/docs/ref/std/algebra) | | | `Semigroup` | [algebra](/docs/ref/std/algebra) | | | `SemiRelaxedConvolve` | [ntt](/docs/ref/std/ntt) | | | `SemiRelaxedConvolve.new` | [ntt](/docs/ref/std/ntt) | O(b.len) | | `SemiRelaxedConvolve.push` | [ntt](/docs/ref/std/ntt) | O(log^2 k) amortized | | `Semiring` | [algebra](/docs/ref/std/algebra) | | | `Settle` | [heap](/docs/ref/std/heap) | | | `Settle.better` | [heap](/docs/ref/std/heap) | | | `Settle.get` | [heap](/docs/ref/std/heap) | O(1) expected | | `Settle.offer` | [heap](/docs/ref/std/heap) | O(log n) amortized, `n` the offers so far | | `Settle.pop` | [heap](/docs/ref/std/heap) | O(log n) amortized, `n` the offers so far | | `Settle.settled` | [heap](/docs/ref/std/heap) | O(1) expected | | `Settle.sift_down` | [heap](/docs/ref/std/heap) | | | `Settle.sift_up` | [heap](/docs/ref/std/heap) | | | `Sieve` | [math](/docs/ref/std/math) | | | `Sieve.div_count_table` | [math](/docs/ref/std/math) | O(n) | | `Sieve.div_sum_table` | [math](/docs/ref/std/math) | O(n) | | `Sieve.divisors` | [math](/docs/ref/std/math) | O(log x) to start, O(1) per divisor | | `Sieve.factor` | [math](/docs/ref/std/math) | O(log x) | | `Sieve.is_prime` | [math](/docs/ref/std/math) | O(1) | | `Sieve.mobius` | [math](/docs/ref/std/math) | O(log x) | | `Sieve.mobius_table` | [math](/docs/ref/std/math) | O(n) | | `Sieve.new` | [math](/docs/ref/std/math) | O(n) time and memory | | `Sieve.phi` | [math](/docs/ref/std/math) | O(log x) | | `Sieve.phi_table` | [math](/docs/ref/std/math) | O(n) | | `Sign` | [math](/docs/ref/std/math) | | | `Slice` | [seq](/docs/ref/std/seq) | | | `Slice.is_empty` | [seq](/docs/ref/std/seq) | O(1) | | `Slice.iter` | [seq](/docs/ref/std/seq) | O(1) per step | | `Slice.keys` | [seq](/docs/ref/std/seq) | O(1) | | `Slice.len` | [seq](/docs/ref/std/seq) | O(1) | | `SortedBag` | [bag](/docs/ref/std/bag) | | | `SortedBag.absorb` | [bag](/docs/ref/std/bag) | O(min(n, m) log(n + m)) expected | | `SortedBag.add` | [bag](/docs/ref/std/bag) | O(log n) expected | | `SortedBag.add_many` | [bag](/docs/ref/std/bag) | O(log n) expected, independent of `c` | | `SortedBag.add_unique` | [bag](/docs/ref/std/bag) | | | `SortedBag.clear` | [bag](/docs/ref/std/bag) | O(1) | | `SortedBag.contains` | [bag](/docs/ref/std/bag) | O(log n) expected | | `SortedBag.count` | [bag](/docs/ref/std/bag) | O(log n) expected | | `SortedBag.count_of` | [bag](/docs/ref/std/bag) | O(1) | | `SortedBag.cursor_at` | [bag](/docs/ref/std/bag) | O(log n) expected | | `SortedBag.cursor_first` | [bag](/docs/ref/std/bag) | O(log n) expected | | `SortedBag.cursor_ge` | [bag](/docs/ref/std/bag) | O(log n) expected | | `SortedBag.cursor_gt` | [bag](/docs/ref/std/bag) | O(log n) expected | | `SortedBag.cursor_last` | [bag](/docs/ref/std/bag) | O(log n) expected | | `SortedBag.cursor_le` | [bag](/docs/ref/std/bag) | O(log n) expected | | `SortedBag.cursor_lt` | [bag](/docs/ref/std/bag) | O(log n) expected | | `SortedBag.distinct` | [bag](/docs/ref/std/bag) | O(1) | | `SortedBag.drain` | [bag](/docs/ref/std/bag) | O(k log n) expected for `k` removed elements | | `SortedBag.drain_range` | [bag](/docs/ref/std/bag) | O(log n + k) expected for `k` removed | | `SortedBag.entries` | [bag](/docs/ref/std/bag) | O(1) amortized per step | | `SortedBag.entries_rev` | [bag](/docs/ref/std/bag) | O(1) amortized per step | | `SortedBag.erase_at` | [bag](/docs/ref/std/bag) | | | `SortedBag.first` | [bag](/docs/ref/std/bag) | O(1) | | `SortedBag.first_true` | [bag](/docs/ref/std/bag) | O(log n) expected calls of `ok` | | `SortedBag.hi_ok` | [bag](/docs/ref/std/bag) | | | `SortedBag.insert_at` | [bag](/docs/ref/std/bag) | | | `SortedBag.is_empty` | [bag](/docs/ref/std/bag) | O(1) | | `SortedBag.join` | [bag](/docs/ref/std/bag) | O(log n) expected | | `SortedBag.key_of` | [bag](/docs/ref/std/bag) | O(1) | | `SortedBag.last` | [bag](/docs/ref/std/bag) | O(1) | | `SortedBag.last_true` | [bag](/docs/ref/std/bag) | O(log n) expected calls of `ok` | | `SortedBag.len` | [bag](/docs/ref/std/bag) | O(1) | | `SortedBag.lo_ok` | [bag](/docs/ref/std/bag) | | | `SortedBag.make_node` | [bag](/docs/ref/std/bag) | | | `SortedBag.merge` | [bag](/docs/ref/std/bag) | | | `SortedBag.move_out` | [bag](/docs/ref/std/bag) | | | `SortedBag.new` | [bag](/docs/ref/std/bag) | O(1) | | `SortedBag.next_cursor` | [bag](/docs/ref/std/bag) | O(1) amortized, O(log n) worst case | | `SortedBag.nth` | [bag](/docs/ref/std/bag) | O(log n) expected | | `SortedBag.of` | [bag](/docs/ref/std/bag) | O(n log n) expected | | `SortedBag.pop_first` | [bag](/docs/ref/std/bag) | O(log n) expected | | `SortedBag.pop_last` | [bag](/docs/ref/std/bag) | O(log n) expected | | `SortedBag.prev_cursor` | [bag](/docs/ref/std/bag) | O(1) amortized, O(log n) worst case | | `SortedBag.pull` | [bag](/docs/ref/std/bag) | | | `SortedBag.range` | [bag](/docs/ref/std/bag) | O(1) to make; see `SortedRange` for each query | | `SortedBag.range_each` | [bag](/docs/ref/std/bag) | | | `SortedBag.range_each_rev` | [bag](/docs/ref/std/bag) | | | `SortedBag.range_first` | [bag](/docs/ref/std/bag) | | | `SortedBag.range_last` | [bag](/docs/ref/std/bag) | | | `SortedBag.range_len` | [bag](/docs/ref/std/bag) | | | `SortedBag.rank` | [bag](/docs/ref/std/bag) | O(log n) expected | | `SortedBag.rank_le` | [bag](/docs/ref/std/bag) | | | `SortedBag.refresh` | [bag](/docs/ref/std/bag) | | | `SortedBag.remove` | [bag](/docs/ref/std/bag) | O(log n) expected | | `SortedBag.remove_all` | [bag](/docs/ref/std/bag) | O(log n) expected | | `SortedBag.reserve` | [bag](/docs/ref/std/bag) | O(cap) when the pool grows, O(1) otherwise | | `SortedBag.split_at` | [bag](/docs/ref/std/bag) | O(log n + s log n) expected, `s` the smaller side's distinct keys | | `SortedBag.split_lt` | [bag](/docs/ref/std/bag) | | | `SortedBag.sub_of` | [bag](/docs/ref/std/bag) | | | `SortedBag.sum` | [bag](/docs/ref/std/bag) | O(n) | | `SortedBag.take` | [bag](/docs/ref/std/bag) | O(1) | | `SortedBag.take_first` | [bag](/docs/ref/std/bag) | O(log n) expected | | `SortedBag.to_list` | [bag](/docs/ref/std/bag) | O(n) | | `SortedMap` | [bag](/docs/ref/std/bag) | | | `SortedMap.absorb` | [bag](/docs/ref/std/bag) | O(min(n, m) log(n + m)) expected | | `SortedMap.at` | [bag](/docs/ref/std/bag) | | | `SortedMap.clear` | [bag](/docs/ref/std/bag) | O(1) | | `SortedMap.contains` | [bag](/docs/ref/std/bag) | O(log n) expected | | `SortedMap.drain` | [bag](/docs/ref/std/bag) | O(k log n) expected for `k` removed entries | | `SortedMap.each_rev` | [bag](/docs/ref/std/bag) | O(1) amortized per step | | `SortedMap.entry` | [bag](/docs/ref/std/bag) | | | `SortedMap.first` | [bag](/docs/ref/std/bag) | O(1) | | `SortedMap.first_ge` | [bag](/docs/ref/std/bag) | O(log n) expected | | `SortedMap.first_gt` | [bag](/docs/ref/std/bag) | O(log n) expected | | `SortedMap.first_true` | [bag](/docs/ref/std/bag) | O(log n) expected calls of `ok` | | `SortedMap.get` | [bag](/docs/ref/std/bag) | O(log n) expected | | `SortedMap.is_empty` | [bag](/docs/ref/std/bag) | O(1) | | `SortedMap.items` | [bag](/docs/ref/std/bag) | O(1) to make, O(1) amortized per step | | `SortedMap.join` | [bag](/docs/ref/std/bag) | O(log n) expected | | `SortedMap.keys` | [bag](/docs/ref/std/bag) | O(1) to make, O(1) amortized per step | | `SortedMap.last` | [bag](/docs/ref/std/bag) | O(1) | | `SortedMap.last_le` | [bag](/docs/ref/std/bag) | O(log n) expected | | `SortedMap.last_lt` | [bag](/docs/ref/std/bag) | O(log n) expected | | `SortedMap.last_true` | [bag](/docs/ref/std/bag) | O(log n) expected calls of `ok` | | `SortedMap.len` | [bag](/docs/ref/std/bag) | O(1) | | `SortedMap.new` | [bag](/docs/ref/std/bag) | O(1) | | `SortedMap.nth` | [bag](/docs/ref/std/bag) | O(log n) expected | | `SortedMap.pop_first` | [bag](/docs/ref/std/bag) | O(log n) expected | | `SortedMap.pop_last` | [bag](/docs/ref/std/bag) | O(log n) expected | | `SortedMap.rank` | [bag](/docs/ref/std/bag) | O(log n) expected | | `SortedMap.remove` | [bag](/docs/ref/std/bag) | O(log n) expected | | `SortedMap.reserve` | [bag](/docs/ref/std/bag) | O(cap) when the pool grows, O(1) otherwise | | `SortedMap.set` | [bag](/docs/ref/std/bag) | O(log n) expected | | `SortedMap.split_at` | [bag](/docs/ref/std/bag) | O(log n) expected | | `SortedMap.take` | [bag](/docs/ref/std/bag) | O(1) | | `SortedMap.values` | [bag](/docs/ref/std/bag) | O(1) to make, O(1) amortized per step | | `SortedRange` | [bag](/docs/ref/std/bag) | | | `SortedRange.each` | [bag](/docs/ref/std/bag) | O(log n + k) expected for `k` keys visited | | `SortedRange.first` | [bag](/docs/ref/std/bag) | O(log n) expected | | `SortedRange.is_empty` | [bag](/docs/ref/std/bag) | O(log n) expected | | `SortedRange.last` | [bag](/docs/ref/std/bag) | O(log n) expected | | `SortedRange.len` | [bag](/docs/ref/std/bag) | O(log n) expected | | `SortedRange.rev` | [bag](/docs/ref/std/bag) | O(log n + k) expected for `k` keys visited | | `SortedSet` | [bag](/docs/ref/std/bag) | | | `SortedSet.absorb` | [bag](/docs/ref/std/bag) | O(min(n, m) log(n + m)) expected | | `SortedSet.add` | [bag](/docs/ref/std/bag) | O(log n) expected | | `SortedSet.clear` | [bag](/docs/ref/std/bag) | O(1) | | `SortedSet.contains` | [bag](/docs/ref/std/bag) | O(log n) expected | | `SortedSet.drain` | [bag](/docs/ref/std/bag) | O(k log n) expected for `k` removed keys | | `SortedSet.each` | [bag](/docs/ref/std/bag) | O(1) amortized per step | | `SortedSet.each_rev` | [bag](/docs/ref/std/bag) | O(1) amortized per step | | `SortedSet.first` | [bag](/docs/ref/std/bag) | O(1) | | `SortedSet.first_true` | [bag](/docs/ref/std/bag) | O(log n) expected calls of `ok` | | `SortedSet.is_empty` | [bag](/docs/ref/std/bag) | O(1) | | `SortedSet.join` | [bag](/docs/ref/std/bag) | O(log n) expected | | `SortedSet.last` | [bag](/docs/ref/std/bag) | O(1) | | `SortedSet.last_true` | [bag](/docs/ref/std/bag) | O(log n) expected calls of `ok` | | `SortedSet.len` | [bag](/docs/ref/std/bag) | O(1) | | `SortedSet.new` | [bag](/docs/ref/std/bag) | O(1) | | `SortedSet.nth` | [bag](/docs/ref/std/bag) | O(log n) expected | | `SortedSet.of` | [bag](/docs/ref/std/bag) | O(n log n) expected | | `SortedSet.pop_first` | [bag](/docs/ref/std/bag) | O(log n) expected | | `SortedSet.pop_last` | [bag](/docs/ref/std/bag) | O(log n) expected | | `SortedSet.range` | [bag](/docs/ref/std/bag) | O(1) to make; see `SortedRange` for each query | | `SortedSet.range_each` | [bag](/docs/ref/std/bag) | | | `SortedSet.range_each_rev` | [bag](/docs/ref/std/bag) | | | `SortedSet.range_first` | [bag](/docs/ref/std/bag) | | | `SortedSet.range_last` | [bag](/docs/ref/std/bag) | | | `SortedSet.range_len` | [bag](/docs/ref/std/bag) | | | `SortedSet.rank` | [bag](/docs/ref/std/bag) | O(log n) expected | | `SortedSet.remove` | [bag](/docs/ref/std/bag) | O(log n) expected | | `SortedSet.reserve` | [bag](/docs/ref/std/bag) | O(cap) when the pool grows, O(1) otherwise | | `SortedSet.set` | [bag](/docs/ref/std/bag) | O(log n) expected | | `SortedSet.split_at` | [bag](/docs/ref/std/bag) | O(log n + s log n) expected, `s` the smaller side's size | | `SortedSet.sum` | [bag](/docs/ref/std/bag) | O(log n) expected | | `SortedSet.take` | [bag](/docs/ref/std/bag) | O(1) | | `SortedSet.to_list` | [bag](/docs/ref/std/bag) | O(n) | | `SosOver` | [ntt](/docs/ref/std/ntt) | | | `SparseFenwick2D` | [fenwick](/docs/ref/std/fenwick) | | | `SparseFenwick2D.add` | [fenwick](/docs/ref/std/fenwick) | O(log^2 n) | | `SparseFenwick2D.add_point` | [fenwick](/docs/ref/std/fenwick) | O(1) amortized | | `SparseFenwick2D.build` | [fenwick](/docs/ref/std/fenwick) | O(n log n) for `n` registered points; memory O(n log n) | | `SparseFenwick2D.corner` | [fenwick](/docs/ref/std/fenwick) | | | `SparseFenwick2D.fold` | [fenwick](/docs/ref/std/fenwick) | O(log^2 n) | | `SparseFenwick2D.new` | [fenwick](/docs/ref/std/fenwick) | O(1) | | `SparseIntervalMap` | [interval](/docs/ref/std/interval) | | | `SparseIntervalMap.assign` | [interval](/docs/ref/std/interval) | O((1 + removed) log runs) amortized | | `SparseIntervalMap.each` | [interval](/docs/ref/std/interval) | O(1) per run | | `SparseIntervalMap.each_rev` | [interval](/docs/ref/std/interval) | O(1) per run | | `SparseIntervalMap.get` | [interval](/docs/ref/std/interval) | O(log runs) | | `SparseIntervalMap.merge_at` | [interval](/docs/ref/std/interval) | | | `SparseIntervalMap.new` | [interval](/docs/ref/std/interval) | O(1) | | `SparseIntervalMap.range` | [interval](/docs/ref/std/interval) | O(log runs + k) for `k` pieces | | `SparseIntervalMap.run_at` | [interval](/docs/ref/std/interval) | O(log runs) | | `SparseIntervalMap.runs` | [interval](/docs/ref/std/interval) | O(1) | | `SparseIntervalMap.split` | [interval](/docs/ref/std/interval) | | | `SparseIntervalMap.update` | [interval](/docs/ref/std/interval) | O((1 + touched) log runs) | | `SparseIntervalSet` | [interval](/docs/ref/std/interval) | | | `SparseIntervalSet.add` | [interval](/docs/ref/std/interval) | O((1 + merged) log runs) amortized | | `SparseIntervalSet.contains` | [interval](/docs/ref/std/interval) | O(log runs) | | `SparseIntervalSet.covered` | [interval](/docs/ref/std/interval) | O(1) | | `SparseIntervalSet.each` | [interval](/docs/ref/std/interval) | O(1) per interval | | `SparseIntervalSet.new` | [interval](/docs/ref/std/interval) | O(1) | | `SparseIntervalSet.next_gap` | [interval](/docs/ref/std/interval) | O(log runs) | | `SparseIntervalSet.remove` | [interval](/docs/ref/std/interval) | O((1 + split) log runs) amortized | | `SparseIntervalSet.runs` | [interval](/docs/ref/std/interval) | O(1) | | `SparseSet` | [marks](/docs/ref/std/marks) | | | `SparseSet.add` | [marks](/docs/ref/std/marks) | O(1) | | `SparseSet.clear` | [marks](/docs/ref/std/marks) | O(1) | | `SparseSet.contains` | [marks](/docs/ref/std/marks) | O(1) | | `SparseSet.each` | [marks](/docs/ref/std/marks) | O(len) | | `SparseSet.is_empty` | [marks](/docs/ref/std/marks) | O(1) | | `SparseSet.len` | [marks](/docs/ref/std/marks) | O(1) | | `SparseSet.new` | [marks](/docs/ref/std/marks) | O(\|D\|) | | `SparseSet.remove` | [marks](/docs/ref/std/marks) | O(1) | | `SparseTable` | [sparse](/docs/ref/std/sparse) | | | `SparseTable.all` | [sparse](/docs/ref/std/sparse) | O(1) | | `SparseTable.fold` | [sparse](/docs/ref/std/sparse) | O(1) | | `SparseTable.get` | [sparse](/docs/ref/std/sparse) | O(1) | | `SparseTable.new` | [sparse](/docs/ref/std/sparse) | O(\|D\| log \|D\|) time and memory, `op` called O(\|D\| log \|D\|) times | | `SparseTable.try_fold` | [sparse](/docs/ref/std/sparse) | O(1) | | `SparseTable2D` | [sparse](/docs/ref/std/sparse) | | | `SparseTable2D.at` | [sparse](/docs/ref/std/sparse) | | | `SparseTable2D.fold` | [sparse](/docs/ref/std/sparse) | O(1) | | `SparseTable2D.get` | [sparse](/docs/ref/std/sparse) | O(1) | | `SparseTable2D.new` | [sparse](/docs/ref/std/sparse) | O(\|R\| \|C\| log \|R\| log \|C\|) time and memory | | `SparseTable2D.try_fold` | [sparse](/docs/ref/std/sparse) | O(1) | | `Step` | [dp](/docs/ref/std/dp) | | | `Step.prune` | [dp](/docs/ref/std/dp) | O(1) | | `SubproductTree` | [poly](/docs/ref/std/poly) | | | `SubproductTree.eval` | [poly](/docs/ref/std/poly) | O((deg f + m) log^2 m) | | `SubproductTree.eval_transposed` | [poly](/docs/ref/std/poly) | O(m log^2 m) | | `SubproductTree.interpolate` | [poly](/docs/ref/std/poly) | O(m log^2 m) | | `SubproductTree.new` | [poly](/docs/ref/std/poly) | O(m log^2 m) time, O(m log m) space | | `SubseqStep` | [seq](/docs/ref/std/seq) | | | `SubseqStep.prune` | [seq](/docs/ref/std/seq) | O(1) | | `Subset` | [subset](/docs/ref/std/subset) | | | `Subset.complement` | [subset](/docs/ref/std/subset) | O(1) | | `Subset.contains` | [subset](/docs/ref/std/subset) | O(1) | | `Subset.empty` | [subset](/docs/ref/std/subset) | O(1) | | `Subset.first` | [subset](/docs/ref/std/subset) | O(1) | | `Subset.full` | [subset](/docs/ref/std/subset) | O(1) | | `Subset.items` | [subset](/docs/ref/std/subset) | O(1) per member | | `Subset.len` | [subset](/docs/ref/std/subset) | O(1) | | `Subset.set` | [subset](/docs/ref/std/subset) | O(1) | | `Subset.shifted` | [subset](/docs/ref/std/subset) | O(1) | | `Subset.single` | [subset](/docs/ref/std/subset) | O(1) | | `Subset.subsets` | [subset](/docs/ref/std/subset) | O(1) per subset, `2^s.len` subsets | | `Subset.supersets` | [subset](/docs/ref/std/subset) | O(1) per superset, `2^(\|B\| - s.len)` supersets | | `Subset.with` | [subset](/docs/ref/std/subset) | O(1) | | `Subset.without` | [subset](/docs/ref/std/subset) | O(1) | | `Subset.bitand` | [subset](/docs/ref/std/subset) | | | `Subset.bitor` | [subset](/docs/ref/std/subset) | | | `Subset.bitxor` | [subset](/docs/ref/std/subset) | | | `Subset.sub` | [subset](/docs/ref/std/subset) | | | `SuffixArray` | [strings](/docs/ref/std/strings) | | | `SuffixArray.arg_min` | [strings](/docs/ref/std/strings) | | | `SuffixArray.compare` | [strings](/docs/ref/std/strings) | O(1) | | `SuffixArray.count` | [strings](/docs/ref/std/strings) | O(\|pat\| log n) | | `SuffixArray.distinct` | [strings](/docs/ref/std/strings) | O(n) | | `SuffixArray.find_all` | [strings](/docs/ref/std/strings) | O(\|pat\| log n + occurrences) | | `SuffixArray.is_empty` | [strings](/docs/ref/std/strings) | O(1) | | `SuffixArray.kth_distinct` | [strings](/docs/ref/std/strings) | O(log n) | | `SuffixArray.lcp_between` | [strings](/docs/ref/std/strings) | O(1) | | `SuffixArray.lcp_of_ranks` | [strings](/docs/ref/std/strings) | O(1) | | `SuffixArray.lcp_range` | [strings](/docs/ref/std/strings) | O(log n) | | `SuffixArray.len` | [strings](/docs/ref/std/strings) | O(1) | | `SuffixArray.new` | [strings](/docs/ref/std/strings) | O(n) for `Str` and small integer alphabets, O(n log n) otherwise | | `SuffixArray.rank_range` | [strings](/docs/ref/std/strings) | O(\|pat\| log n) | | `SuffixArray.split` | [strings](/docs/ref/std/strings) | O(1) | | `SuffixAutomaton` | [strings](/docs/ref/std/strings) | | | `SuffixAutomaton.add_empty_state` | [strings](/docs/ref/std/strings) | | | `SuffixAutomaton.add_word` | [strings](/docs/ref/std/strings) | O(\|word\|) amortized | | `SuffixAutomaton.clone_state` | [strings](/docs/ref/std/strings) | | | `SuffixAutomaton.contains` | [strings](/docs/ref/std/strings) | O(\|word\|) | | `SuffixAutomaton.distinct` | [strings](/docs/ref/std/strings) | O(states) | | `SuffixAutomaton.endpos_tree` | [strings](/docs/ref/std/strings) | O(states) | | `SuffixAutomaton.find` | [strings](/docs/ref/std/strings) | | | `SuffixAutomaton.first_pos` | [strings](/docs/ref/std/strings) | | | `SuffixAutomaton.kth_substring` | [strings](/docs/ref/std/strings) | O(states * \|A\|) | | `SuffixAutomaton.lcs` | [strings](/docs/ref/std/strings) | | | `SuffixAutomaton.len` | [strings](/docs/ref/std/strings) | O(1) | | `SuffixAutomaton.link` | [strings](/docs/ref/std/strings) | | | `SuffixAutomaton.longest` | [strings](/docs/ref/std/strings) | | | `SuffixAutomaton.new` | [strings](/docs/ref/std/strings) | O(\|A\|) | | `SuffixAutomaton.occ_counts` | [strings](/docs/ref/std/strings) | | | `SuffixAutomaton.of` | [strings](/docs/ref/std/strings) | O(\|s\| * \|A\|) memory, O(\|s\|) amortized time | | `SuffixAutomaton.push` | [strings](/docs/ref/std/strings) | | | `SuffixAutomaton.reset` | [strings](/docs/ref/std/strings) | O(1) | | `SuffixAutomaton.root` | [strings](/docs/ref/std/strings) | O(1) | | `SuffixAutomaton.shortest` | [strings](/docs/ref/std/strings) | | | `SuffixAutomaton.states` | [strings](/docs/ref/std/strings) | O(states) | | `SuffixAutomaton.step` | [strings](/docs/ref/std/strings) | | | `SuffixAutomaton.topo_order` | [strings](/docs/ref/std/strings) | | | `SuffixTreeEdge` | [strings](/docs/ref/std/strings) | | | `Sweep` | [window](/docs/ref/std/window) | | | `Sweep.move` | [window](/docs/ref/std/window) | O(\|dl\| + \|dr\|) pushes and pops, where `dl` and `dr` are the moves of the two ends | | `Sweep.new` | [window](/docs/ref/std/window) | O(1), plus `start.len` pushes when `start` is given | | `Sweep.range` | [window](/docs/ref/std/window) | O(1) | | `SweepAdd` | [prefix](/docs/ref/std/prefix) | | | `SweepAdd.add` | [prefix](/docs/ref/std/prefix) | O(1) | | `SweepAdd.advance` | [prefix](/docs/ref/std/prefix) | O(1) | | `SweepAdd.current` | [prefix](/docs/ref/std/prefix) | O(1) | | `SweepAdd.new` | [prefix](/docs/ref/std/prefix) | O(\|D\|) time and space | | `Target` | [graph](/docs/ref/std/graph) | | | `Target.to` | [graph](/docs/ref/std/graph) | O(1) | | `TimeStep` | [timetree](/docs/ref/std/timetree) | | | `TimeTree` | [timetree](/docs/ref/std/timetree) | | | `TimeTree.add_interval` | [timetree](/docs/ref/std/timetree) | O(log q) | | `TimeTree.add_range` | [timetree](/docs/ref/std/timetree) | O(log q) | | `TimeTree.emit_dfs` | [timetree](/docs/ref/std/timetree) | | | `TimeTree.event` | [timetree](/docs/ref/std/timetree) | O(1) | | `TimeTree.link` | [timetree](/docs/ref/std/timetree) | | | `TimeTree.new` | [timetree](/docs/ref/std/timetree) | O(q) time and memory | | `TimeTree.run` | [timetree](/docs/ref/std/timetree) | O(q + m log q) callback calls for `m` scheduled intervals, O(log q) extra stack | | `TimeTree.run_node` | [timetree](/docs/ref/std/timetree) | | | `TimeTree.steps` | [timetree](/docs/ref/std/timetree) | O(q + m log q) time and memory for `m` scheduled intervals | | `TimeTree.walk` | [timetree](/docs/ref/std/timetree) | O(1) amortized per step, O(log q) extra stack | | `Track` | [window](/docs/ref/std/window) | | | `Track.pop` | [window](/docs/ref/std/window) | | | `Track.push` | [window](/docs/ref/std/window) | | | `Tracked` | [window](/docs/ref/std/window) | | | `Tracked.pop` | [window](/docs/ref/std/window) | one call of `remove` | | `Tracked.push` | [window](/docs/ref/std/window) | one call of `add` | | `Tracked.state` | [window](/docs/ref/std/window) | O(1) | | `Trie` | [strings](/docs/ref/std/strings) | | | `Trie.add` | [strings](/docs/ref/std/strings) | | | `Trie.clear` | [strings](/docs/ref/std/strings) | O(1) | | `Trie.contains` | [strings](/docs/ref/std/strings) | O(\|word\|) | | `Trie.count` | [strings](/docs/ref/std/strings) | | | `Trie.count_less` | [strings](/docs/ref/std/strings) | O(\|word\| * \|A\|) | | `Trie.count_prefix` | [strings](/docs/ref/std/strings) | | | `Trie.ends_at` | [strings](/docs/ref/std/strings) | | | `Trie.find` | [strings](/docs/ref/std/strings) | | | `Trie.is_empty` | [strings](/docs/ref/std/strings) | O(1) | | `Trie.kth` | [strings](/docs/ref/std/strings) | O(depth * \|A\|) | | `Trie.len` | [strings](/docs/ref/std/strings) | O(1) | | `Trie.new` | [strings](/docs/ref/std/strings) | O(\|A\|) | | `Trie.pass_at` | [strings](/docs/ref/std/strings) | | | `Trie.remove` | [strings](/docs/ref/std/strings) | | | `Trie.root` | [strings](/docs/ref/std/strings) | O(1) | | `Trie.step` | [strings](/docs/ref/std/strings) | | | `TwoSat` | [graph](/docs/ref/std/graph) | | | `TwoSat.add_eq` | [graph](/docs/ref/std/graph) | O(1) amortized | | `TwoSat.add_or` | [graph](/docs/ref/std/graph) | O(1) amortized | | `TwoSat.add_xor` | [graph](/docs/ref/std/graph) | O(1) amortized | | `TwoSat.at_most_one` | [graph](/docs/ref/std/graph) | O(k) amortized | | `TwoSat.clause` | [graph](/docs/ref/std/graph) | | | `TwoSat.implies` | [graph](/docs/ref/std/graph) | O(1) amortized | | `TwoSat.must` | [graph](/docs/ref/std/graph) | O(1) amortized | | `TwoSat.new` | [graph](/docs/ref/std/graph) | O(\|X\|) | | `TwoSat.solve` | [graph](/docs/ref/std/graph) | O(\|X\| + clauses) | | `Undo` | [window](/docs/ref/std/window) | | | `Undo.mark` | [window](/docs/ref/std/window) | | | `Undo.undo_to` | [window](/docs/ref/std/window) | | | `Undoing` | [window](/docs/ref/std/window) | | | `Undoing.pop` | [window](/docs/ref/std/window) | O(log n) applications of `add` amortized | | `Undoing.push` | [window](/docs/ref/std/window) | O(1) applications of `add` amortized | | `Undoing.push_entry` | [window](/docs/ref/std/window) | | | `Undoing.state` | [window](/docs/ref/std/window) | O(1) | | `Vec` | [geometry](/docs/ref/std/geometry) | | | `Vec.add` | [geometry](/docs/ref/std/geometry) | | | `Vec.angle` | [geometry](/docs/ref/std/geometry) | O(1) | | `Vec.cross` | [geometry](/docs/ref/std/geometry) | O(1) | | `Vec.dist` | [geometry](/docs/ref/std/geometry) | O(1) | | `Vec.dist2` | [geometry](/docs/ref/std/geometry) | O(1) | | `Vec.div` | [geometry](/docs/ref/std/geometry) | | | `Vec.dot` | [geometry](/docs/ref/std/geometry) | O(1) | | `Vec.from_angle` | [geometry](/docs/ref/std/geometry) | O(1) | | `Vec.len` | [geometry](/docs/ref/std/geometry) | O(1) | | `Vec.mul` | [geometry](/docs/ref/std/geometry) | | | `Vec.neg` | [geometry](/docs/ref/std/geometry) | | | `Vec.norm2` | [geometry](/docs/ref/std/geometry) | O(1) | | `Vec.perp` | [geometry](/docs/ref/std/geometry) | O(1) | | `Vec.perp_cw` | [geometry](/docs/ref/std/geometry) | O(1) | | `Vec.rot` | [geometry](/docs/ref/std/geometry) | O(1) | | `Vec.sub` | [geometry](/docs/ref/std/geometry) | | | `Vec.unit` | [geometry](/docs/ref/std/geometry) | O(1) | | `Vec3` | [geometry](/docs/ref/std/geometry) | | | `Vec3.add` | [geometry](/docs/ref/std/geometry) | | | `Vec3.cross` | [geometry](/docs/ref/std/geometry) | O(1) | | `Vec3.dist` | [geometry](/docs/ref/std/geometry) | O(1) | | `Vec3.dist2` | [geometry](/docs/ref/std/geometry) | O(1) | | `Vec3.div` | [geometry](/docs/ref/std/geometry) | | | `Vec3.dot` | [geometry](/docs/ref/std/geometry) | O(1) | | `Vec3.len` | [geometry](/docs/ref/std/geometry) | O(1) | | `Vec3.mul` | [geometry](/docs/ref/std/geometry) | | | `Vec3.neg` | [geometry](/docs/ref/std/geometry) | | | `Vec3.norm2` | [geometry](/docs/ref/std/geometry) | O(1) | | `Vec3.rot` | [geometry](/docs/ref/std/geometry) | O(1) | | `Vec3.sub` | [geometry](/docs/ref/std/geometry) | | | `Vec3.unit` | [geometry](/docs/ref/std/geometry) | O(1) | | `Version` | [persistent](/docs/ref/std/persistent) | | | `VirtualTree` | [tree](/docs/ref/std/tree) | | | `Visit` | [graph](/docs/ref/std/graph) | | | `Walk` | [graph](/docs/ref/std/graph) | | | `Walk.vertices` | [graph](/docs/ref/std/graph) | O(1) to make, O(1) per vertex | | `WaveletMatrix` | [segtree](/docs/ref/std/segtree) | | | `WaveletMatrix.below` | [segtree](/docs/ref/std/segtree) | | | `WaveletMatrix.count_in` | [segtree](/docs/ref/std/segtree) | O(log V) | | `WaveletMatrix.count_lt` | [segtree](/docs/ref/std/segtree) | O(log V) | | `WaveletMatrix.kth` | [segtree](/docs/ref/std/segtree) | O(log V) | | `WaveletMatrix.new` | [segtree](/docs/ref/std/segtree) | O(\|D\| log V) time and memory | | `WaveletMatrix.next_val` | [segtree](/docs/ref/std/segtree) | O(log V) | | `WaveletMatrix.ones` | [segtree](/docs/ref/std/segtree) | | | `WaveletMatrix.prev_val` | [segtree](/docs/ref/std/segtree) | O(log V) | | `WaveletMatrix.quantile_sum` | [segtree](/docs/ref/std/segtree) | O(log V) | | `WaveletMatrix.rank` | [segtree](/docs/ref/std/segtree) | O(log V) | | `Weighted` | [graph](/docs/ref/std/graph) | | | `Weighted.w` | [graph](/docs/ref/std/graph) | O(1) plus the cost of `f` under `weighted` | | `WeightedNext` | [graph](/docs/ref/std/graph) | | | `Window` | [window](/docs/ref/std/window) | | | `Window.all` | [window](/docs/ref/std/window) | O(1) | | `Window.drop_front` | [window](/docs/ref/std/window) | | | `Window.len` | [window](/docs/ref/std/window) | O(1) | | `Window.new` | [window](/docs/ref/std/window) | O(1) | | `Window.pop` | [window](/docs/ref/std/window) | O(1) amortized calls of `op` | | `Window.push` | [window](/docs/ref/std/window) | O(1) amortized calls of `op` | | `Window.push_back` | [window](/docs/ref/std/window) | | | `Window.pop` | [window](/docs/ref/std/window) | | | `Window.push` | [window](/docs/ref/std/window) | | | `Wire` | [io](/docs/ref/std/io) | | | `Wire.ask` | [io](/docs/ref/std/io) | O(\|query\|) plus the read of one `T` | | `Wire.new` | [io](/docs/ref/std/io) | O(1) | | `Word.rev` | [algebra](/docs/ref/std/algebra) | | | `Word.rev` | [tree](/docs/ref/std/tree) | | | `XorBasis` | [matrix](/docs/ref/std/matrix) | | | `XorBasis.add` | [matrix](/docs/ref/std/matrix) | O(W) | | `XorBasis.basis_vecs` | [matrix](/docs/ref/std/matrix) | O(W) time and space | | `XorBasis.contains` | [matrix](/docs/ref/std/matrix) | O(W) | | `XorBasis.intersect` | [matrix](/docs/ref/std/matrix) | O(W^2) | | `XorBasis.kth` | [matrix](/docs/ref/std/matrix) | O(W^2) | | `XorBasis.max_xor` | [matrix](/docs/ref/std/matrix) | O(W) | | `XorBasis.merge` | [matrix](/docs/ref/std/matrix) | O(W * o.rank) | | `XorBasis.min_xor` | [matrix](/docs/ref/std/matrix) | O(W) | | `XorBasis.monoid` | [matrix](/docs/ref/std/matrix) | O(W) (for the identity) | | `XorBasis.new` | [matrix](/docs/ref/std/matrix) | O(W) | | `XorBasis.rank` | [matrix](/docs/ref/std/matrix) | O(1) | | `XorBasis.reduce` | [matrix](/docs/ref/std/matrix) | O(W) | | `XorTrie` | [bitset](/docs/ref/std/bitset) | | | `XorTrie.add` | [bitset](/docs/ref/std/bitset) | O(bits) time, up to `bits` new nodes | | `XorTrie.child` | [bitset](/docs/ref/std/bitset) | | | `XorTrie.clear` | [bitset](/docs/ref/std/bitset) | O(1) | | `XorTrie.contains` | [bitset](/docs/ref/std/bitset) | O(bits) | | `XorTrie.count` | [bitset](/docs/ref/std/bitset) | O(bits) | | `XorTrie.count_xor_less` | [bitset](/docs/ref/std/bitset) | O(bits) | | `XorTrie.extreme_xor` | [bitset](/docs/ref/std/bitset) | | | `XorTrie.is_empty` | [bitset](/docs/ref/std/bitset) | O(1) | | `XorTrie.kth_xor` | [bitset](/docs/ref/std/bitset) | O(bits) | | `XorTrie.leaf` | [bitset](/docs/ref/std/bitset) | | | `XorTrie.len` | [bitset](/docs/ref/std/bitset) | O(1) | | `XorTrie.max_xor` | [bitset](/docs/ref/std/bitset) | O(bits) | | `XorTrie.mex_xor` | [bitset](/docs/ref/std/bitset) | O(bits) | | `XorTrie.min_xor` | [bitset](/docs/ref/std/bitset) | O(bits) | | `XorTrie.new` | [bitset](/docs/ref/std/bitset) | O(1) | | `XorTrie.remove` | [bitset](/docs/ref/std/bitset) | O(bits) | | `XorTrie.reserve` | [bitset](/docs/ref/std/bitset) | O(nodes) time and space | | `XorTrie.walk` | [bitset](/docs/ref/std/bitset) | | | `XorTrie.xor_all` | [bitset](/docs/ref/std/bitset) | O(1) | --- # interval URL: /docs/ref/std/interval Generated from [spec/std/interval.cp](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/interval.cp) by `cpl doc --format json`. ## `IntervalMap` ```cp pub struct IntervalMap ``` A total partition of domain `D` into maximal contiguous half-open runs, each carrying a value of type `T`. Adjacent runs always have distinct values (`==` runs coalesce automatically). `new` is O(1); `from` is O(D.K); `at`, `run_at`, and `assign_point` are O(log runs); `assign` is amortized O((1 + overwritten) log runs); `each` is O(runs); `runs` is O(1). [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/interval.cp#L12) ### `IntervalMap.new` ```cp fn new(init: T) -> IntervalMap ``` A map that gives every position of `D` the value `init`: one run, or None when `D` is empty. - **cost**: O(1) - **empty**: an empty `D` gives zero runs - **traps**: never Examples: - `IntervalMap<0..5, Int>(0).runs == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/interval.cp#L21) ### `IntervalMap.from` ```cp fn from(a: [D]T) -> IntervalMap ``` The map holding `a[i]` at every position `i`, stored as maximal runs of equal values. - **cost**: O(|D|) - **empty**: an empty `a` gives zero runs - **order**: positions keep the domain `D` of `a` - **traps**: never Examples: - `IntervalMap.from([1, 1, 2]).runs == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/interval.cp#L33) ### `IntervalMap.runs` ```cp fn runs(self) -> Int ``` The number of maximal runs, i.e. one more than the number of adjacent positions whose values differ (zero for an empty `D`). - **cost**: O(1) - **traps**: never Examples: - `IntervalMap.from([1, 2, 2, 1]).runs == 3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/interval.cp#L53) ### `IntervalMap.get` ```cp fn get(self, i: D) -> T ``` The value at position `i`. - **cost**: O(log runs) - **traps**: when `i` is outside `D` Examples: - `IntervalMap.from([1, 1, 2]).get(2) == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/interval.cp#L61) ### `IntervalMap.run_at` ```cp fn run_at(self, i: D) -> (range: Range, val: T) ``` The maximal run containing position `i` and its value. - **cost**: O(log runs) - **order**: the run's positions in ascending order - **traps**: when `i` is outside `D` Examples: - `IntervalMap.from([1, 1, 2]).run_at(1).range == 0..2` - `IntervalMap.from([1, 1, 2]).run_at(1).val == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/interval.cp#L71) ### `IntervalMap.assign` ```cp fn assign(mut self, r: Range, val: T, on_old: (Range, T) -> () = (_, _) => ()) ``` Give every position of `r` the value `val`, then merge it with equal neighbouring runs so all runs stay maximal. `on_old` is called with each overwritten piece (an old run overlapping `r`, clipped to `r`) and its old value; the map is fully repainted when `assign` returns. - **cost**: O((1 + overwritten) log runs) amortized - **empty**: changes nothing and calls `on_old` never - **order**: `on_old` sees pieces in ascending positions - **traps**: when a non-empty `r` reaches outside `D` Examples: - `var m = IntervalMap<0..5, Int>(0); m.assign(1..3, 7); m.runs == 3` - `var m = IntervalMap<0..5, Int>(0); m.assign(1..3, 7); m.assign(1..3, 0); m.runs == 1` - `var m = IntervalMap.from([1, 1, 2, 2]); var old: List = []; m.assign(1..3, 9, on_old: (_, v) => old.push(v)); old == [1, 2]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/interval.cp#L86) ### `IntervalMap.assign_point` ```cp fn assign_point(mut self, i: D, val: T) -> T ``` Give position `i` the value `val` and return the value it had. - **cost**: O(log runs) - **traps**: when `i` is outside `D` Examples: - `var m = IntervalMap.from([1, 2]); m.assign_point(0, 5) == 1 and m.get(0) == 5` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/interval.cp#L149) ### `IntervalMap.each` ```cp fn each(self) -> yields (range: Range, val: T) ``` Every maximal run with its value. - **cost**: O(1) per run - **empty**: yields nothing for an empty `D` - **order**: ascending positions - **traps**: never Examples: - `IntervalMap.from([1, 1, 2]).each().map(p => p.val).collect() == [1, 2]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/interval.cp#L162) ### `IntervalMap.set` ```cp fn set(mut self, i: D, val: T) ``` Give position `i` the value `val`; `assign_point` without the old value, and the write-through place for `m[i] = val`. - **cost**: O(log runs) - **traps**: when `i` is outside `D` Examples: - `var m = IntervalMap.from([1, 1]); m.set(1, 3); m.runs == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/interval.cp#L172) ### `IntervalMap.range` ```cp fn range(self, r: Range) -> yields (range: Range, val: T) ``` Every run overlapping `r`, clipped to `r`, with its value. Clipping can make the first and last pieces shorter than their runs; they are not merged with anything. - **cost**: O(log runs + k) for `k` pieces - **empty**: yields nothing - **order**: ascending positions - **traps**: when a non-empty `r` reaches outside `D` Examples: - `IntervalMap.from([1, 1, 2]).range(1..3).map(p => p.range).collect() == [1..2, 2..3]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/interval.cp#L183) ### `IntervalMap.each_rev` ```cp fn each_rev(self) -> yields (range: Range, val: T) ``` Every maximal run with its value, last first. - **cost**: O(1) per run - **empty**: yields nothing for an empty `D` - **order**: descending positions - **traps**: never Examples: - `IntervalMap.from([1, 1, 2]).each_rev().map(p => p.val).collect() == [2, 1]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/interval.cp#L199) ### `IntervalMap.first_where` ```cp fn first_where(self, from: Cut, ok: T -> Bool) -> ?D ``` The first position right of the cut `from` whose value satisfies `ok`, or `None`. Calls `ok` once per run, not per position. - **cost**: O(log runs + skipped) for `skipped` runs that fail `ok` - **ties**: the first position in key order - **traps**: never Examples: - `IntervalMap.from([1, 1, 2]).first_where((0..0).r, v => v == 2) == Some(2)` - `IntervalMap.from([1, 1, 2]).first_where((0..1).r, v => v == 1) == Some(1)` - `IntervalMap.from([1, 1, 2]).first_where((0..3).r, v => true) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/interval.cp#L215) ## `IntervalSet` ```cp pub struct IntervalSet ``` O(runs) space. Dynamic union of disjoint maximal half-open intervals over domain `D` (KACTL `IntervalContainer`). Maintains total `covered` length in O(1). [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/interval.cp#L225) ### `IntervalSet.new` ```cp fn new() -> IntervalSet ``` An empty set of positions of `D`. - **cost**: O(1) - **traps**: never Examples: - `IntervalSet<0..10>().covered == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/interval.cp#L234) ### `IntervalSet.add` ```cp fn add(mut self, r: Range) ``` Add every position of `r`, merging runs that overlap or touch it into one maximal run. - **cost**: O((1 + merged) log runs) amortized - **empty**: changes nothing - **traps**: when a non-empty `r` reaches outside `D` Examples: - `var s = IntervalSet<0..10>(); s.add(1..3); s.add(3..5); s.runs == 1 and s.covered == 4` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/interval.cp#L243) ### `IntervalSet.remove` ```cp fn remove(mut self, r: Range) ``` Remove every position of `r`; a run straddling an end of `r` is cut there. - **cost**: O((1 + split) log runs) amortized - **empty**: changes nothing - **traps**: when a non-empty `r` reaches outside `D` Examples: - `var s = IntervalSet<0..10>(); s.add(0..5); s.remove(1..2); s.runs == 2 and s.covered == 4` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/interval.cp#L266) ### `IntervalSet.contains` ```cp fn contains(self, i: D) -> Bool ``` Whether position `i` is in the set. - **cost**: O(log runs) - **traps**: when `i` is outside `D` Examples: - `var s = IntervalSet<0..10>(); s.add(2..4); s.contains(3) and not s.contains(4)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/interval.cp#L289) ### `IntervalSet.contains_range` ```cp fn contains_range(self, r: Range) -> Bool ``` Whether every position of `r` is in the set, i.e. one run covers `r`. - **cost**: O(log runs) - **empty**: `true` - **traps**: when a non-empty `r` reaches outside `D` Examples: - `var s = IntervalSet<0..10>(); s.add(2..4); s.add(4..6); s.contains_range(3..6) == true` - `var s = IntervalSet<0..10>(); s.add(2..4); s.contains_range(3..5) == false` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/interval.cp#L301) ### `IntervalSet.run_at` ```cp fn run_at(self, i: D) -> ?Range ``` The maximal run containing position `i`, or `None` when `i` is not in the set. - **cost**: O(log runs) - **order**: the run's positions in ascending order - **traps**: when `i` is outside `D` Examples: - `var s = IntervalSet<0..10>(); s.add(2..4); s.run_at(3) == Some(2..4)` - `var s = IntervalSet<0..10>(); s.add(2..4); s.run_at(4) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/interval.cp#L314) ### `IntervalSet.next_covered` ```cp fn next_covered(self, from: D) -> ?D ``` The first position at or after `from` that is in the set, or `None`. - **cost**: O(log runs) - **traps**: when `from` is outside `D` Examples: - `var s = IntervalSet<0..10>(); s.add(5..7); s.next_covered(2) == Some(5)` - `var s = IntervalSet<0..10>(); s.add(5..7); s.next_covered(7) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/interval.cp#L326) ### `IntervalSet.next_gap` ```cp fn next_gap(self, from: D) -> ?D ``` The first position at or after `from` that is not in the set (a dynamic mex), or `None` when every position from `from` to the end of `D` is covered. - **cost**: O(log runs) - **traps**: when `from` is outside `D` Examples: - `var s = IntervalSet<0..10>(); s.add(0..3); s.next_gap(1) == Some(3)` - `var s = IntervalSet<0..10>(); s.add(5..10); s.next_gap(6) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/interval.cp#L339) ### `IntervalSet.covered` ```cp fn covered(self) -> Int ``` The number of positions in the set. - **cost**: O(1) - **traps**: never Examples: - `var s = IntervalSet<0..10>(); s.add(1..3); s.add(6..7); s.covered == 3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/interval.cp#L351) ### `IntervalSet.runs` ```cp fn runs(self) -> Int ``` The number of maximal runs. - **cost**: O(1) - **traps**: never Examples: - `var s = IntervalSet<0..10>(); s.add(1..3); s.add(6..7); s.runs == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/interval.cp#L359) ### `IntervalSet.each` ```cp fn each(self) -> yields Range ``` Every maximal run. - **cost**: O(1) per run - **empty**: yields nothing for an empty set - **order**: ascending positions - **traps**: never Examples: - `var s = IntervalSet<0..10>(); s.add(6..7); s.add(1..3); s.each().collect() == [1..3, 6..7]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/interval.cp#L369) ## `SparseIntervalSet` ```cp pub struct SparseIntervalSet ``` O(runs) space. Dynamic union of disjoint half-open integer intervals `[lo, hi)` over unbounded `Int` coordinates. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/interval.cp#L373) ### `SparseIntervalSet.new` ```cp fn new() -> SparseIntervalSet ``` An empty set of `Int` coordinates, unbounded in both directions. - **cost**: O(1) - **traps**: never Examples: - `SparseIntervalSet().covered == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/interval.cp#L382) ### `SparseIntervalSet.add` ```cp fn add(mut self, r: Range) ``` Add every coordinate of the half-open `r`, merging runs that overlap or touch it. - **cost**: O((1 + merged) log runs) amortized - **empty**: changes nothing - **traps**: never Examples: - `var s = SparseIntervalSet(); s.add(-5..0); s.add(0..5); s.runs == 1 and s.covered == 10` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/interval.cp#L391) ### `SparseIntervalSet.remove` ```cp fn remove(mut self, r: Range) ``` Remove every coordinate of the half-open `r`; a run straddling an end of `r` is cut there. - **cost**: O((1 + split) log runs) amortized - **empty**: changes nothing - **traps**: never Examples: - `var s = SparseIntervalSet(); s.add(0..10); s.remove(3..4); s.runs == 2 and s.covered == 9` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/interval.cp#L415) ### `SparseIntervalSet.contains` ```cp fn contains(self, x: Int) -> Bool ``` Whether the coordinate `x` is in the set. - **cost**: O(log runs) - **traps**: never Examples: - `var s = SparseIntervalSet(); s.add(10..20); s.contains(19) and not s.contains(20)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/interval.cp#L439) ### `SparseIntervalSet.next_gap` ```cp fn next_gap(self, x: Int) -> Int ``` The least coordinate `>= x` that is not in the set; always exists, since the set is finite. - **cost**: O(log runs) - **traps**: never Examples: - `var s = SparseIntervalSet(); s.add(0..3); s.next_gap(1) == 3` - `SparseIntervalSet().next_gap(-7) == -7` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/interval.cp#L449) ### `SparseIntervalSet.covered` ```cp fn covered(self) -> Int ``` The total number of coordinates in the set. - **cost**: O(1) - **traps**: never Examples: - `var s = SparseIntervalSet(); s.add(0..3); s.add(10..12); s.covered == 5` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/interval.cp#L459) ### `SparseIntervalSet.runs` ```cp fn runs(self) -> Int ``` The number of maximal intervals. - **cost**: O(1) - **traps**: never Examples: - `var s = SparseIntervalSet(); s.add(0..3); s.add(10..12); s.runs == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/interval.cp#L467) ### `SparseIntervalSet.each` ```cp fn each(self) -> yields Range ``` Every maximal interval. - **cost**: O(1) per interval - **empty**: yields nothing for an empty set - **order**: ascending coordinates - **traps**: never Examples: - `var s = SparseIntervalSet(); s.add(10..12); s.add(0..3); s.each().collect() == [0..3, 10..12]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/interval.cp#L477) ## `SparseIntervalMap` ```cp pub struct SparseIntervalMap ``` Interval partition map over unbounded `Int` coordinates `[lo, hi)` (ODT without coordinate compression). Maintains maximal constant runs; `assign` is O((1 + removed) log runs) amortized. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/interval.cp#L518) ### `SparseIntervalMap.split` ```cp fn split(mut self, x: Int) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/interval.cp#L524) ### `SparseIntervalMap.merge_at` ```cp fn merge_at(mut self, x: Int) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/interval.cp#L530) ### `SparseIntervalMap.new` ```cp fn new(lo: Int, hi: Int, init: T) -> SparseIntervalMap ``` A map giving every coordinate of `lo..hi` the value `init`: one run, or None when `lo == hi`. - **cost**: O(1) - **traps**: when `lo > hi` Examples: - `SparseIntervalMap(0, 1_000_000_000, 0).runs == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/interval.cp#L542) ### `SparseIntervalMap.runs` ```cp fn runs(self) -> Int ``` The number of maximal runs of equal values. - **cost**: O(1) - **traps**: never Examples: - `var m = SparseIntervalMap(0, 10, 0); m.assign(3..5, 1); m.runs == 3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/interval.cp#L553) ### `SparseIntervalMap.get` ```cp fn get(self, i: Int) -> T ``` The value at coordinate `i`. - **cost**: O(log runs) - **traps**: when `i` is outside `lo..hi` Examples: - `var m = SparseIntervalMap(0, 10, 0); m.assign(3..5, 1); m.get(4) == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/interval.cp#L561) ### `SparseIntervalMap.run_at` ```cp fn run_at(self, i: Int) -> (range: Range, val: T) ``` The maximal run containing coordinate `i` and its value. - **cost**: O(log runs) - **order**: the run's coordinates in ascending order - **traps**: when `i` is outside `lo..hi` Examples: - `var m = SparseIntervalMap(0, 10, 0); m.assign(3..5, 1); m.run_at(7).range == 5..10` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/interval.cp#L571) ### `SparseIntervalMap.assign` ```cp fn assign(mut self, r: Range, val: T, on_old: (Range, T) -> () = (_, _) => ()) ``` Give every coordinate of `r` the value `val`, then merge with equal neighbouring runs. `on_old` is called with each old run overlapping `r`, clipped to `r`, and its old value; the map is fully repainted when `assign` returns. - **cost**: O((1 + removed) log runs) amortized - **empty**: changes nothing and calls `on_old` never - **order**: `on_old` sees pieces in ascending coordinates - **traps**: when a non-empty `r` reaches outside `lo..hi` Examples: - `var m = SparseIntervalMap(0, 10, 0); m.assign(3..5, 1); m.assign(5..7, 1); m.runs == 3` - `var m = SparseIntervalMap(0, 10, 0); m.assign(3..5, 1); var old: List = []; m.assign(4..6, 2, on_old: (_, v) => old.push(v)); old == [1, 0]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/interval.cp#L586) ### `SparseIntervalMap.update` ```cp fn update(mut self, r: Range, f: T -> T) ``` Replace the value `v` of every run overlapping `r`, clipped to `r`, with `f(v)`, then merge equal neighbours. `f` is called once per piece, in ascending order. - **cost**: O((1 + touched) log runs) - **empty**: changes nothing and calls `f` never - **traps**: when a non-empty `r` reaches outside `lo..hi` Examples: - `var m = SparseIntervalMap(0, 10, 0); m.assign(3..5, 1); m.update(0..4, v => v + 1); m.get(0) == 1 and m.get(3) == 2 and m.get(4) == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/interval.cp#L609) ### `SparseIntervalMap.range` ```cp fn range(self, r: Range) -> yields (range: Range, val: T) ``` Every run overlapping `r`, clipped to `r`, with its value. - **cost**: O(log runs + k) for `k` pieces - **empty**: yields nothing - **order**: ascending coordinates - **traps**: when a non-empty `r` reaches outside `lo..hi` Examples: - `var m = SparseIntervalMap(0, 10, 0); m.assign(3..5, 1); m.range(4..6).map(p => p.range).collect() == [4..5, 5..6]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/interval.cp#L632) ### `SparseIntervalMap.each` ```cp fn each(self) -> yields (range: Range, val: T) ``` Every maximal run with its value. - **cost**: O(1) per run - **empty**: yields nothing when `lo == hi` - **order**: ascending coordinates - **traps**: never Examples: - `var m = SparseIntervalMap(0, 10, 0); m.assign(3..5, 1); m.each().map(p => p.val).collect() == [0, 1, 0]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/interval.cp#L650) ### `SparseIntervalMap.each_rev` ```cp fn each_rev(self) -> yields (range: Range, val: T) ``` Every maximal run with its value, last first. - **cost**: O(1) per run - **empty**: yields nothing when `lo == hi` - **order**: descending coordinates - **traps**: never Examples: - `var m = SparseIntervalMap(0, 10, 0); m.assign(3..5, 1); m.each_rev().map(p => p.range).collect() == [5..10, 3..5, 0..3]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/interval.cp#L660) --- # io URL: /docs/ref/std/io Generated from [spec/std/io.cp](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/io.cp) by `cpl doc --format json`. ## `Wire` ```cp pub struct Wire() ``` Interactive mode. Constructing one (`let wire = Wire()`) makes every read and the program's exit flush stdout first; a program that never builds one never flushes early. O(1). [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/io.cp#L22) ### `Wire.new` ```cp fn new() -> Wire ``` A handle that puts the program in interactive mode (spec/core/10-io.md §10.4). From construction on, every read and every exit flushes stdout first, so a query is never stuck in the buffer while the program waits for its answer. A program that never constructs a `Wire` never flushes early. Constructing a second `Wire` is allowed and changes nothing. - **cost**: O(1) - **traps**: never Examples: - `let wire = Wire(); print(1); true` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/io.cp#L32) ### `Wire.ask` ```cp fn ask(self, query: Str) -> T ``` Print `query` and a newline, flush, then read one answer as the `T` the call site expects. `T` comes from the expected type, as with `read`: `fn ask(x: Int, y: Int) -> Int = wire.ask("? {x} {y}")`. The answer is read with the same rules as `read()`. - **cost**: O(|query|) plus the read of one `T` - **traps**: when input ends before an answer, or the answer is not a valid `T` Examples: - `let wire = Wire(); let x: Int = wire.ask("? 1 2"); x == 7` (stdin `7`) [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/io.cp#L44) ## `io` ```cp pub context io ``` Compile-time I/O settings: 0/1-based counted domains, field separator, `yes` words, and float precision. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/io.cp#L66) --- # lazy URL: /docs/ref/std/lazy Generated from [spec/std/lazy.cp](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/lazy.cp) by `cpl doc --format json`. ## `Flip` ```cp pub struct Flip(now: T, flipped: T) ``` Paired aggregate `(now, flipped)` for range-toggle / complement updates (`SegTree(op, a, act: flip)`). Build the toggle action with `flip_action(m)` (tag `Bool`: `true` swaps `now` and `flipped`). [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/lazy.cp#L9) ### `Flip.of` ```cp fn of(on: Bool, x: T, id: T) -> Flip ``` The leaf for one element that is currently `on` or off: `Flip(x, id)` when `on`, else `Flip(id, x)`. `now` is the value the element contributes as it stands and `flipped` what it would contribute after one toggle. - **cost**: O(1) - **traps**: never Examples: - `Flip.of(true, 5, 0).now == 5` - `Flip.of(false, 5, 0).flipped == 5` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/lazy.cp#L18) ### `Flip.op` ```cp fn op(m: M) -> Monoid> ``` The monoid on pairs that folds both halves with `m` independently: `op(a, b) == Flip(m(a.now, b.now), m(a.flipped, b.flipped))`, identity `Flip(id, id)` with `id` from `Monoid.of(m)`. - **cost**: O(1) - **traps**: never (an `m` without a known identity is a compile-time error) Examples: - `Flip.op(+).op(Flip(1, 0), Flip(0, 1)).now == 1` - `Flip.op(+).id.flipped == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/lazy.cp#L29) ## `LazyTreap` ```cp pub struct LazyTreap( ``` Arena-backed randomized treap with subtree-size-aware lazy tag propagation. Supports value-ordered insertion (`insert`, using `before`) for slope-trick / priority structures with lazy updates, and 0-based implicit sequence operations (`push`, `insert_at`, `apply_range`, `get`). `apply(v, left_sz, f)` updates a node's value given its left subtree size; `split(f, left_sz)` splits a tag `f` for the left and right subtrees (default `(f, f)`); `compose(new_f, old_f)` applies `old_f` first then `new_f`. `insert`, `insert_at`, `push`, `apply_range`, `get` are O(log n) expected; `apply_all` is O(1); `take(k)` is O(k + log n); `to_list` is O(n). Memory is O(n) in a contiguous node arena; sizes and priorities are `0..2^31`, so a treap holds fewer than 2^31 elements. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/lazy.cp#L126) ### `LazyTreap.new` ```cp fn new( apply: (T, Int, F) -> T, compose: (F, F) -> F, split: (F, Int) -> (F, F) = (f, _) => (f, f), before: (T, T) -> Bool = (_, _) => false, ) -> LazyTreap ``` An empty treap. `apply(v, k, f)` is element `v` after tag `f`, where `k` is the number of elements before it in the run the tag was applied to (so tags may depend on rank); `compose(new_f, old_f)` is `old_f` then `new_f`; `split(f, k)` gives the tags for the left child and for the right child of a node with `k` elements on its left (default `(f, f)`, for tags that ignore rank; a rank-dependent tag needs a `split` that shifts the right child's ranks by `k + 1`); `before(x, y)` orders value insertion (default never, so `insert` appends). - **cost**: O(1) - **empty**: the new treap is empty - **traps**: never Examples: - `LazyTreap(apply: (v, k, f) => v + f, compose: (g, f) => g + f).len == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/lazy.cp#L147) ### `LazyTreap.priority` ```cp fn priority(mut self) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/lazy.cp#L155) ### `LazyTreap.sz_of` ```cp fn sz_of(self, u: ?Int) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/lazy.cp#L157) ### `LazyTreap.len` ```cp fn len(self) -> Int ``` The number of elements stored. - **cost**: O(1) - **traps**: never Examples: - `var t = LazyTreap(apply: (v, k, f) => v + f, compose: (g, f) => g + f); t.push(4); t.len == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/lazy.cp#L167) ### `LazyTreap.reserve` ```cp fn reserve(mut self, n: Int) ``` Make room for `n` elements in total, so pushes up to that size never regrow the node arena. A smaller `n` than the current capacity changes nothing. - **cost**: O(n) when it grows, else O(1) - **traps**: when `n >= 2^31` (the size bound) Examples: - `var t = LazyTreap(apply: (v, k, f) => v + f, compose: (g, f) => g + f); t.reserve(10); t.len == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/lazy.cp#L175) ### `LazyTreap.is_empty` ```cp fn is_empty(self) -> Bool ``` Whether the treap holds no elements. - **cost**: O(1) - **traps**: never Examples: - `LazyTreap(apply: (v, k, f) => v + f, compose: (g, f) => g + f).is_empty == true` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/lazy.cp#L182) ### `LazyTreap.put` ```cp fn put(mut self, u: ?Int, f: F) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/lazy.cp#L184) ### `LazyTreap.down` ```cp fn down(mut self, i: Int) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/lazy.cp#L193) ### `LazyTreap.pull` ```cp fn pull(mut self, i: Int) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/lazy.cp#L201) ### `LazyTreap.split_val` ```cp fn split_val(mut self, u: ?Int, x: T) -> (?Int, ?Int) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/lazy.cp#L204) ### `LazyTreap.ins` ```cp fn ins(mut self, u: ?Int, idx: Int, x: T, p: Int) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/lazy.cp#L219) ### `LazyTreap.split_pos` ```cp fn split_pos(mut self, u: ?Int, k: Int) -> (?Int, ?Int) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/lazy.cp#L236) ### `LazyTreap.merge` ```cp fn merge(mut self, a: ?Int, b: ?Int) -> ?Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/lazy.cp#L252) ### `LazyTreap.insert` ```cp fn insert(mut self, x: T) ``` Insert `x` before the first element `e` with `before(x, e)`, or at the end when there is None. With a strict order for `before`, a sorted treap stays sorted and `x` goes after the elements equal to it. - **cost**: O(log n) expected - **ties**: after every equal element - **traps**: when the treap already holds `2^31 - 1` elements Examples: - `var t = LazyTreap(apply: (v, k, f) => v + f, compose: (g, f) => g + f, before: (x, y) => x < y); t.insert(3); t.insert(1); t.insert(2); t.to_list() == [1, 2, 3]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/lazy.cp#L275) ### `LazyTreap.push` ```cp fn push(mut self, x: T) ``` Append `x` at the end of the sequence. - **cost**: O(log n) expected - **traps**: when the treap already holds `2^31 - 1` elements Examples: - `var t = LazyTreap(apply: (v, k, f) => v + f, compose: (g, f) => g + f); t.push(1); t.push(2); t.to_list() == [1, 2]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/lazy.cp#L286) ### `LazyTreap.insert_at` ```cp fn insert_at(mut self, pos: Int, x: T) ``` Insert `x` so that it becomes the element at 0-based position `pos`; `pos == len` appends. - **cost**: O(log n) expected - **traps**: when `pos < 0` or `pos > len` Examples: - `var t = LazyTreap(apply: (v, k, f) => v + f, compose: (g, f) => g + f); t.push(1); t.push(3); t.insert_at(1, 2); t.to_list() == [1, 2, 3]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/lazy.cp#L296) ### `LazyTreap.apply_all` ```cp fn apply_all(mut self, f: F) ``` Apply tag `f` to every element, as one tag on the root; ranks `k` count from the first element. - **cost**: O(1) - **empty**: changes nothing - **traps**: never Examples: - `var t = LazyTreap(apply: (v, k, f) => v + f, compose: (g, f) => g + f); t.push(1); t.push(2); t.apply_all(10); t.to_list() == [11, 12]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/lazy.cp#L309) ### `LazyTreap.apply_range` ```cp fn apply_range(mut self, lo: Int, hi: Int, f: F) ``` Apply tag `f` to the elements at positions `lo..hi`; ranks `k` count from position `lo`. - **cost**: O(log n) expected - **empty**: `lo == hi` changes nothing - **traps**: when `lo < 0`, `hi > len` or `lo > hi` Examples: - `var t = LazyTreap(apply: (v, k, f) => v + f, compose: (g, f) => g + f); t.push(0); t.push(0); t.push(0); t.apply_range(1, 3, 5); t.to_list() == [0, 5, 5]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/lazy.cp#L318) ### `LazyTreap.apply` ```cp fn apply(mut self, r: Range, f: F) ``` Apply tag `f` to the elements at the positions of `r`; `apply_range` with a range. - **cost**: O(log n) expected - **empty**: changes nothing - **traps**: when a non-empty `r` reaches outside `0..len` Examples: - `var t = LazyTreap(apply: (v, k, f) => v + f, compose: (g, f) => g + f); t.push(1); t.push(2); t.apply(1..2, 10); t.to_list() == [1, 12]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/lazy.cp#L332) ### `LazyTreap.reverse` ```cp fn reverse(mut self, r: Range) ``` Reverse the order of the elements at positions `r`. Tags applied earlier keep their effect on the elements they reached; a later tag sees the new order. - **cost**: O(log n) expected - **empty**: changes nothing - **traps**: when a non-empty `r` reaches outside `0..len` Examples: - `var t = LazyTreap(apply: (v, k, f) => v + f, compose: (g, f) => g + f); t.push(1); t.push(2); t.push(3); t.reverse(0..2); t.to_list() == [2, 1, 3]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/lazy.cp#L342) ### `LazyTreap.erase_at` ```cp fn erase_at(mut self, pos: Int) -> T ``` Remove the element at 0-based position `pos` and return it with every pending tag applied. - **cost**: O(log n) expected - **traps**: when `pos < 0` or `pos >= len` Examples: - `var t = LazyTreap(apply: (v, k, f) => v + f, compose: (g, f) => g + f); t.push(1); t.push(2); t.apply_all(5); t.erase_at(0) == 6 and t.to_list() == [7]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/lazy.cp#L349) ### `LazyTreap.erase_range` ```cp fn erase_range(mut self, r: Range) ``` Remove the elements at positions `r`; later elements move down by `r.len`. - **cost**: O(log n) expected - **empty**: changes nothing - **traps**: when a non-empty `r` reaches outside `0..len` Examples: - `var t = LazyTreap(apply: (v, k, f) => v + f, compose: (g, f) => g + f); t.push(1); t.push(2); t.push(3); t.erase_range(0..2); t.to_list() == [3]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/lazy.cp#L362) ### `LazyTreap.split_at` ```cp fn split_at(mut self, k: Int) -> LazyTreap ``` Split off the elements at positions `k..len` into a new treap with the same `apply`, `compose`, `split` and `before`, and return it; `self` keeps positions `0..k`. Pending tags travel with the elements they cover. - **cost**: O(log n) expected - **traps**: when `k < 0` or `k > len` Examples: - `var t = LazyTreap(apply: (v, k, f) => v + f, compose: (g, f) => g + f); t.push(1); t.push(2); t.push(3); let u = t.split_at(1); t.to_list() == [1] and u.to_list() == [2, 3]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/lazy.cp#L377) ### `LazyTreap.copy_from` ```cp fn copy_from(mut self, src: LazyTreap, u: ?Int) -> ?Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/lazy.cp#L385) ### `LazyTreap.append` ```cp fn append(mut self, mut other: LazyTreap) ``` Move every element of `other` onto the end of `self`, in order, leaving `other` empty. Both treaps must use the same functions; `self`'s are kept. - **cost**: O(log n) expected - **empty**: an empty `other` changes nothing - **traps**: when the total reaches `2^31` elements Examples: - `var t = LazyTreap(apply: (v, k, f) => v + f, compose: (g, f) => g + f); t.push(1); var u = t.split_at(1); u.push(5); t.append(mut u); t.to_list() == [1, 5] and u.is_empty` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/lazy.cp#L400) ### `LazyTreap.get` ```cp fn get(mut self, pos: Int) -> T ``` The element at 0-based position `pos` with every pending tag on its path applied. Tags are pushed down along the path, which is why it takes `mut self`; the sequence does not change. - **cost**: O(log n) expected - **traps**: when `pos < 0` or `pos >= len` Examples: - `var t = LazyTreap(apply: (v, k, f) => v + f, compose: (g, f) => g + f); t.push(1); t.push(2); t.apply(0..1, 4); t.get(0) == 5` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/lazy.cp#L413) ### `LazyTreap.walk` ```cp fn walk(self, u: ?Int, pend: ?F, lim: Int, mut out: List) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/lazy.cp#L433) ### `LazyTreap.take` ```cp fn take(self, k: Int) -> List ``` The first `min(k, len)` elements in order, with pending tags applied. Reads without pushing tags, so the tree is unchanged. - **cost**: O(k + log n) - **empty**: `[]` when `k == 0` or the treap is empty - **order**: sequence order - **traps**: when `k < 0` Examples: - `var t = LazyTreap(apply: (v, k, f) => v + f, compose: (g, f) => g + f); t.push(1); t.push(2); t.push(3); t.take(2) == [1, 2]` - `var t = LazyTreap(apply: (v, k, f) => v + f, compose: (g, f) => g + f); t.push(1); t.take(5) == [1]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/lazy.cp#L464) ### `LazyTreap.to_list` ```cp fn to_list(self) -> List ``` Every element in order, with pending tags applied; `take(len)`. - **cost**: O(n) - **empty**: `[]` - **order**: sequence order - **traps**: never Examples: - `LazyTreap(apply: (v, k, f) => v + f, compose: (g, f) => g + f).to_list() == []` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/lazy.cp#L476) ## `Rope` ```cp pub struct Rope ``` O(n) space. Implicit-key rope over a domain `D` supporting O(log n) expected cut, paste, reverse, range tag `apply`, path queries, and point `get`. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/lazy.cp#L480) ### `Rope.size` ```cp fn size(self, t: Int) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/lazy.cp#L495) ### `Rope.pull` ```cp fn pull(mut self, t: Int) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/lazy.cp#L497) ### `Rope.tag_node` ```cp fn tag_node(mut self, t: Int, x: T) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/lazy.cp#L500) ### `Rope.down` ```cp fn down(mut self, t: Int) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/lazy.cp#L510) ### `Rope.split` ```cp fn split(mut self, t: Int, k: Int) -> (Int, Int) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/lazy.cp#L524) ### `Rope.join` ```cp fn join(mut self, a: Int, b: Int) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/lazy.cp#L539) ### `Rope.find` ```cp fn find(mut self, k0: Int) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/lazy.cp#L553) ### `Rope.emit` ```cp fn emit(mut self, t: Int, mut out: [D]T, mut k: Int) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/lazy.cp#L565) ### `Rope.new` ```cp fn new(a: ?[D]T = None, fill: ?T = None, merge: ?((T, T) -> T) = None) -> Rope ``` A rope over `D` holding the values of `a`, or `fill` at every position. `merge(tag, x)` is how a tag from `apply` combines into a value; without it, a tag overwrites the values it covers. Positions keep their domain `D`; `reverse` moves values, not positions. - **cost**: O(|D|) - **empty**: an empty `D` builds an empty rope - **order**: positions keep the domain `D` (of `a`, when given) - **traps**: when neither or both of `a` and `fill` are given Examples: - `Rope([1, 2, 3]).to_array() == [1, 2, 3]` - `Rope<0..2, Int>(fill: 7).get(1) == 7` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/lazy.cp#L583) ### `Rope.apply` ```cp fn apply(mut self, r: Range, tag: T) ``` Apply `tag` to every value at positions `r`: each becomes `merge(tag, x)`, or `tag` when no `merge` was given. Stored lazily on the covering nodes. - **cost**: O(log n) expected - **empty**: changes nothing - **traps**: when a non-empty `r` reaches outside `D` Examples: - `var r = Rope([1, 2, 3], merge: (t, x) => t + x); r.apply(1..3, 10); r.to_array() == [1, 12, 13]` - `var r = Rope([1, 2, 3]); r.apply(0..2, 7); r.to_array() == [7, 7, 3]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/lazy.cp#L626) ### `Rope.reverse` ```cp fn reverse(mut self, r: Range) ``` Reverse the order of the values at positions `r`; pending tags stay with their values. - **cost**: O(log n) expected - **empty**: changes nothing - **traps**: when a non-empty `r` reaches outside `D` Examples: - `var r = Rope([1, 2, 3]); r.reverse(0..3); r.get(0) == 3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/lazy.cp#L640) ### `Rope.get` ```cp fn get(mut self, i: D) -> T ``` The value currently at position `i`, with pending tags merged in. - **cost**: O(log n) expected - **traps**: when `i` is outside `D` Examples: - `var r = Rope([1, 2, 3]); r.reverse(1..3); r.get(1) == 3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/lazy.cp#L653) ### `Rope.set` ```cp fn set(mut self, i: D, x: T) ``` Overwrite the value currently at position `i` with `x`, replacing any pending tags on it. - **cost**: O(log n) expected - **traps**: when `i` is outside `D` Examples: - `var r = Rope([1, 2, 3]); r.set(1, 9); r.to_array() == [1, 9, 3]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/lazy.cp#L662) ### `Rope.to_array` ```cp fn to_array(mut self) -> [D]T ``` The current values in position order, with every pending tag merged in. - **cost**: O(|D|) - **empty**: an empty array for an empty `D` - **order**: position order of `D` - **traps**: never Examples: - `var r = Rope([1, 2, 3]); r.reverse(0..2); r.to_array() == [2, 1, 3]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/lazy.cp#L673) --- # marks URL: /docs/ref/std/marks Generated from [spec/std/marks.cp](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/marks.cp) by `cpl doc --format json`. ## `Marks` ```cp pub struct Marks ``` A visited/mark set over a domain `D` with O(1) `add`, `remove`, `contains` (`v in m`), and O(1) `clear()`. Memory is one `[D]0..=2_000_000_000` array (4 bytes per element). [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/marks.cp#L14) ### `Marks.new` ```cp fn new() -> Marks ``` An empty mark set over `D`, with its stamp array allocated once. - **cost**: O(|D|) - **empty**: an empty `D` gives a set that can never hold a mark - **traps**: never Examples: - `Marks<0..5>().is_empty` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/marks.cp#L25) ### `Marks.add` ```cp fn add(mut self, v: D) -> Bool ``` Mark `v`. Returns `true` when `v` was unmarked, `false` when it was already marked (and nothing changes). - **cost**: O(1) - **traps**: when `v` is outside `D` Examples: - `var m = Marks<0..5>(); m.add(2) and not m.add(2)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/marks.cp#L33) ### `Marks.remove` ```cp fn remove(mut self, v: D) -> Bool ``` Unmark `v`. Returns `true` when `v` was marked, `false` when it was not (and nothing changes). - **cost**: O(1) - **traps**: when `v` is outside `D` Examples: - `var m = Marks<0..5>(); m.add(2); m.remove(2) and not m.remove(2)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/marks.cp#L44) ### `Marks.contains` ```cp fn contains(self, v: D) -> Bool ``` Whether `v` is marked; also spelled `v in m`. - **cost**: O(1) - **traps**: when `v` is outside `D` Examples: - `var m = Marks<0..5>(); m.add(1); m.contains(1) and not m.contains(0)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/marks.cp#L55) ### `Marks.clear` ```cp fn clear(mut self) ``` Unmark everything by moving to a new generation, without touching the stamp array. Once the generation counter reaches `2_000_000_000` the array is reset to zero, so the cost stays O(1) amortized over the calls. - **cost**: O(1) amortized; O(|D|) on the call that wraps the counter - **traps**: never Examples: - `var m = Marks<0..5>(); m.add(1); m.add(3); m.clear(); m.is_empty and not (1 in m)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/marks.cp#L64) ### `Marks.len` ```cp fn len(self) -> Int ``` The number of marked positions. - **cost**: O(1) - **traps**: never Examples: - `var m = Marks<0..5>(); m.add(1); m.add(3); m.add(1); m.len == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/marks.cp#L77) ### `Marks.is_empty` ```cp fn is_empty(self) -> Bool ``` Whether no position is marked; `len == 0`. - **cost**: O(1) - **traps**: never Examples: - `var m = Marks<0..5>(); m.add(0); m.remove(0); m.is_empty` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/marks.cp#L85) ## `MarkMap` ```cp pub struct MarkMap ``` Epoch-stamped map over domain `D` with O(1) `get`, `set`, `contains`, `remove`, and `clear()`. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/marks.cp#L89) ### `MarkMap.new` ```cp fn new(default_val: T) -> MarkMap ``` An empty map over `D`. `default_val` fills the value array and is never returned: an absent key reads as `None`. - **cost**: O(|D|) - **empty**: an empty `D` gives a map that can never hold an entry - **traps**: never Examples: - `MarkMap<0..5, Int>(0).is_empty` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/marks.cp#L103) ### `MarkMap.len` ```cp fn len(self) -> Int ``` The number of keys present. - **cost**: O(1) - **traps**: never Examples: - `var m = MarkMap<0..5, Int>(0); m.set(1, 7); m.set(1, 8); m.set(4, 0); m.len == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/marks.cp#L111) ### `MarkMap.is_empty` ```cp fn is_empty(self) -> Bool ``` Whether no key is present; `len == 0`. - **cost**: O(1) - **traps**: never Examples: - `var m = MarkMap<0..5, Int>(0); m.set(2, 1); m.remove(2); m.is_empty` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/marks.cp#L119) ### `MarkMap.contains` ```cp fn contains(self, v: D) -> Bool ``` Whether `v` has a value. A key set to `default_val` is present. - **cost**: O(1) - **traps**: when `v` is outside `D` Examples: - `var m = MarkMap<0..5, Int>(0); m.set(2, 0); m.contains(2) and not m.contains(3)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/marks.cp#L127) ### `MarkMap.get` ```cp fn get(self, v: D) -> ?T ``` The value at `v`, or `None` when `v` is absent. - **cost**: O(1) - **traps**: when `v` is outside `D` Examples: - `var m = MarkMap<0..5, Int>(0); m.set(2, 9); m.get(2) == Some(9) and m.get(3) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/marks.cp#L134) ### `MarkMap.set` ```cp fn set(mut self, v: D, val: T) ``` Give `v` the value `val`, adding `v` when it is absent and overwriting it otherwise. - **cost**: O(1) - **traps**: when `v` is outside `D` Examples: - `var m = MarkMap<0..5, Int>(0); m.set(2, 9); m.set(2, 4); m.get(2) == Some(4)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/marks.cp#L141) ### `MarkMap.remove` ```cp fn remove(mut self, v: D) -> ?T ``` Remove `v` and return the value it had, or `None` (and change nothing) when it was absent. - **cost**: O(1) - **traps**: when `v` is outside `D` Examples: - `var m = MarkMap<0..5, Int>(0); m.set(2, 9); m.remove(2) == Some(9) and m.remove(2) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/marks.cp#L152) ### `MarkMap.clear` ```cp fn clear(mut self) ``` Remove every key by moving to a new generation, without touching the value array; the arrays are reset when the counter reaches `2_000_000_000`, as for `Marks.clear`. - **cost**: O(1) amortized; O(|D|) on the call that wraps the counter - **traps**: never Examples: - `var m = MarkMap<0..5, Int>(0); m.set(2, 9); m.clear(); m.get(2) == None and m.is_empty` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/marks.cp#L164) ## `Interner` ```cp pub struct Interner ``` Online value-to-id interner assigning contiguous `0..len` IDs to distinct keys `K`. `id`, `get`, and `key` are O(1) expected; `len`, `is_empty`, `clear` are O(1). [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/marks.cp#L174) ### `Interner.new` ```cp fn new() -> Interner ``` An empty interner. - **cost**: O(1) - **traps**: never Examples: - `Interner().is_empty` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/marks.cp#L183) ### `Interner.len` ```cp fn len(self) -> Int ``` The number of distinct keys interned so far; ids are exactly `0..len`. - **cost**: O(1) - **traps**: never Examples: - `var t = Interner(); t.id("a"); t.id("b"); t.id("a"); t.len == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/marks.cp#L190) ### `Interner.is_empty` ```cp fn is_empty(self) -> Bool ``` Whether no key has been interned; `len == 0`. - **cost**: O(1) - **traps**: never Examples: - `var t = Interner(); t.id("a"); t.clear(); t.is_empty` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/marks.cp#L198) ### `Interner.clear` ```cp fn clear(mut self) ``` Forget every key, so the next new key gets id `0` again. - **cost**: O(1) - **traps**: never Examples: - `var t = Interner(); t.id("a"); t.id("b"); t.clear(); t.id("b") == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/marks.cp#L206) ### `Interner.id` ```cp fn id(mut self, k: K) -> Int ``` The id of `k`. A new key gets the next id, `len`, so ids follow first-seen order. - **cost**: O(1) expected - **traps**: never Examples: - `var t = Interner(); t.id("x") == 0 and t.id("y") == 1 and t.id("x") == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/marks.cp#L215) ### `Interner.get` ```cp fn get(self, k: K) -> ?Int ``` The id of `k`, or `None` when `k` has not been interned; never adds a key. - **cost**: O(1) expected - **traps**: never Examples: - `var t = Interner(); t.id("x"); t.get("x") == Some(0) and t.get("y") == None and t.len == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/marks.cp#L227) ### `Interner.key` ```cp fn key(self, i: Int) -> K ``` The key whose id is `i`; the inverse of `id`. - **cost**: O(1) - **traps**: when `i` is outside `0..len` Examples: - `var t = Interner(); t.id("x"); t.id("y"); t.key(1) == "y"` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/marks.cp#L234) ### `Interner.contains` ```cp fn contains(self, k: K) -> Bool ``` Whether `k` has been interned; `get(k) != None`. - **cost**: O(1) expected - **traps**: never Examples: - `var t = Interner(); t.id(40); t.contains(40) and not t.contains(41)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/marks.cp#L241) ### `Interner.reserve` ```cp fn reserve(mut self, cap: Int) ``` Allocate room for at least `cap` distinct keys, so the next `cap - len` new keys do not reallocate. Changes no ids. - **cost**: O(cap) - **traps**: when `cap < 0` Examples: - `var t = Interner(); t.reserve(100); t.id(5); t.len == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/marks.cp#L250) ## `SparseSet` ```cp pub struct SparseSet ``` Briggs-Torczon sparse set over domain `D`. O(1) `add`, `remove`, `contains`, `clear` AND O(`len`) iteration over active elements. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/marks.cp#L256) ### `SparseSet.new` ```cp fn new() -> SparseSet ``` An empty sparse set over `D`. - **cost**: O(|D|) - **empty**: an empty `D` gives a set that can never hold an element - **traps**: never Examples: - `SparseSet<0..5>().is_empty` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/marks.cp#L267) ### `SparseSet.len` ```cp fn len(self) -> Int ``` The number of elements. - **cost**: O(1) - **traps**: never Examples: - `var s = SparseSet<0..5>(); s.add(1); s.add(4); s.add(1); s.len == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/marks.cp#L275) ### `SparseSet.is_empty` ```cp fn is_empty(self) -> Bool ``` Whether the set has no elements; `len == 0`. - **cost**: O(1) - **traps**: never Examples: - `var s = SparseSet<0..5>(); s.add(1); s.remove(1); s.is_empty` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/marks.cp#L283) ### `SparseSet.contains` ```cp fn contains(self, v: D) -> Bool ``` Whether `v` is in the set. - **cost**: O(1) - **traps**: when `v` is outside `D` Examples: - `var s = SparseSet<0..5>(); s.add(3); s.contains(3) and not s.contains(2)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/marks.cp#L291) ### `SparseSet.add` ```cp fn add(mut self, v: D) -> Bool ``` Add `v` at the end of the dense order. Returns `true` when `v` was absent, `false` when it was present (and nothing changes). - **cost**: O(1) - **traps**: when `v` is outside `D` Examples: - `var s = SparseSet<0..5>(); s.add(3) and not s.add(3)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/marks.cp#L301) ### `SparseSet.remove` ```cp fn remove(mut self, v: D) -> Bool ``` Remove `v`, moving the last element of the dense order into its slot. Returns `true` when `v` was present, `false` when it was absent (and nothing changes). - **cost**: O(1) - **traps**: when `v` is outside `D` Examples: - `var s = SparseSet<0..5>(); s.add(3); s.add(1); s.add(4); s.remove(3); s.each().collect() == [4, 1]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/marks.cp#L315) ### `SparseSet.clear` ```cp fn clear(mut self) ``` Remove every element by resetting the length; the sparse table is not touched. - **cost**: O(1) - **traps**: never Examples: - `var s = SparseSet<0..5>(); s.add(3); s.clear(); s.is_empty and not s.contains(3)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/marks.cp#L329) ### `SparseSet.each` ```cp fn each(self) -> yields D ``` Every element, in dense order: insertion order, except that each `remove` moved the then-last element into the removed one's slot. - **cost**: O(len) - **empty**: yields nothing for an empty set - **order**: dense order (insertion order adjusted by removals, as above) - **traps**: never Examples: - `var s = SparseSet<0..5>(); s.add(2); s.add(0); s.add(4); s.each().collect() == [2, 0, 4]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/marks.cp#L340) ## `Id` ```cp pub struct Id(raw ``` Compact 4-byte typed handle into an `Arena`. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/marks.cp#L344) ## `Arena` ```cp pub struct Arena ``` Contiguous pool allocator returning compact 4-byte `Id` handles (for user trees, tries, and persistent nodes). [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/marks.cp#L347) ### `Arena.new` ```cp fn new(cap: Int = 0) -> Arena ``` An empty arena with room for `cap` nodes before it reallocates. - **cost**: O(cap) - **traps**: when `cap < 0` Examples: - `Arena(cap: 8).is_empty` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/marks.cp#L355) ### `Arena.len` ```cp fn len(self) -> Int ``` The number of nodes allocated since creation or the last `clear`; valid handles have raw values `0..len`. - **cost**: O(1) - **traps**: never Examples: - `var a = Arena(); a.alloc(5); a.alloc(6); a.len == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/marks.cp#L366) ### `Arena.is_empty` ```cp fn is_empty(self) -> Bool ``` Whether no node is allocated; `len == 0`. - **cost**: O(1) - **traps**: never Examples: - `var a = Arena(); a.alloc(5); a.clear(); a.is_empty` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/marks.cp#L374) ### `Arena.alloc` ```cp fn alloc(mut self, x: T) -> Id ``` Store `x` as a new node and return its handle; handles are issued in order `0, 1, 2, ...`. - **cost**: O(1) amortized - **traps**: when the arena already holds `2_000_000_001` nodes Examples: - `var a = Arena(); a.alloc("p"); a.alloc("q") == Id(1)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/marks.cp#L382) ### `Arena.get` ```cp fn get(self, id: Id) -> T ``` The node behind `id`; also `arena[id]`. it is below `len`; it reads whatever node now holds that slot - **cost**: O(1) - **traps**: when `id` is not below `len`. A handle issued before a `clear` is not detected while Examples: - `var a = Arena(); let i = a.alloc(5); a.alloc(6); a.get(i) == 5` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/marks.cp#L392) ### `Arena.set` ```cp fn set(mut self, id: Id, x: T) ``` Overwrite the node behind `id` with `x`; also `arena[id] = x`. - **cost**: O(1) - **traps**: when `id` is not below `len` (stale handles as in `get`) Examples: - `var a = Arena(); let i = a.alloc(5); a.set(i, 9); a[i] == 9` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/marks.cp#L400) ### `Arena.reserve` ```cp fn reserve(mut self, cap: Int) ``` Allocate room for at least `cap` nodes in total; changes no handle or node. - **cost**: O(cap) - **traps**: when `cap < 0` Examples: - `var a = Arena(); a.reserve(100); a.alloc(1); a.len == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/marks.cp#L408) ### `Arena.clear` ```cp fn clear(mut self) ``` Drop every node, so the next `alloc` returns handle `0` again. Every handle issued before is invalidated. - **cost**: O(1) - **traps**: never Examples: - `var a = Arena(); a.alloc(5); a.clear(); a.alloc(7) == Id(0)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/marks.cp#L417) --- # math URL: /docs/ref/std/math Generated from [spec/std/math.cp](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/math.cp) by `cpl doc --format json`. ## `Sieve` ```cp pub struct Sieve ``` The smallest prime factor of every number up to `n` (0 for 0 and 1), by a linear sieve. O(n) time and memory. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/math.cp#L185) ### `Sieve.new` ```cp fn new(n: Int) -> Sieve ``` A linear sieve up to `n`: the smallest prime factor of every `0..=n` and the primes in `2..=n`, ascending. `spf[0]` and `spf[1]` are 0. Queries take any `x` in `0..=n` (`1..=n` where 0 is meaningless). - **cost**: O(n) time and memory - **traps**: when `n < 0` or `n > 2_000_000_000` Examples: - `Sieve(10).is_prime(7) == true` - `Sieve(0).is_prime(0) == false` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/math.cp#L198) ### `Sieve.is_prime` ```cp fn is_prime(self, x: Int) -> Bool ``` Whether `x` is prime, for `0 <= x <= n`: `spf[x] == x` and `x >= 2`. - **cost**: O(1) - **traps**: when `x` is outside `0..=n` Examples: - `Sieve(10).is_prime(7) == true` - `Sieve(10).is_prime(9) == false` - `Sieve(10).is_prime(1) == false` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/math.cp#L219) ### `Sieve.factor` ```cp fn factor(self, x: Int) -> List<(Int, Int)> ``` The prime factorization of `x` in `1..=n` as `(prime, exponent)` pairs, by repeated `spf`. - **cost**: O(log x) - **order**: smallest prime first; a new `List`, keyed from 0 - **traps**: when `x` is outside `1..=n` Examples: - `Sieve(100).factor(60) == [(2, 2), (3, 1), (5, 1)]` - `Sieve(100).factor(97) == [(97, 1)]` - `Sieve(100).factor(1) == []` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/math.cp#L229) ### `Sieve.phi` ```cp fn phi(self, x: Int) -> Int ``` Euler's totient of `x` in `1..=n`: how many of `1..=x` are coprime to `x`. - **cost**: O(log x) - **traps**: when `x` is outside `1..=n` Examples: - `Sieve(100).phi(36) == 12` - `Sieve(100).phi(1) == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/math.cp#L247) ### `Sieve.mobius` ```cp fn mobius(self, x: Int) -> Int ``` The Mobius function of `x` in `1..=n`: 0 if a square above 1 divides `x`, else -1 to the number of prime factors. - **cost**: O(log x) - **traps**: when `x` is outside `1..=n` Examples: - `Sieve(100).mobius(30) == -1` - `Sieve(100).mobius(12) == 0` - `Sieve(100).mobius(6) == 1` - `Sieve(100).mobius(1) == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/math.cp#L261) ### `Sieve.phi_table` ```cp fn phi_table(self) -> List ``` Euler's totient of every `0..=n`, with `phi[0] == 0`. - **cost**: O(n) - **order**: `phi[k]` at key `k`, `k` in `0..=n`; a new `List` - **traps**: never Examples: - `Sieve(6).phi_table() == [0, 1, 1, 2, 2, 4, 2]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/math.cp#L271) ### `Sieve.mobius_table` ```cp fn mobius_table(self) -> List ``` The Mobius function of every `0..=n`, with `mu[0] == 0` and `mu[1] == 1`. - **cost**: O(n) - **order**: `mu[k]` at key `k`, `k` in `0..=n`; a new `List` - **traps**: never Examples: - `Sieve(6).mobius_table() == [0, 1, -1, -1, 0, -1, 1]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/math.cp#L288) ### `Sieve.div_count_table` ```cp fn div_count_table(self) -> List ``` The number of positive divisors of every `0..=n`, with `d[0] == 0`. - **cost**: O(n) - **order**: `d[k]` at key `k`, `k` in `0..=n`; a new `List` - **traps**: never Examples: - `Sieve(6).div_count_table() == [0, 1, 2, 2, 3, 2, 4]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/math.cp#L305) ### `Sieve.div_sum_table` ```cp fn div_sum_table(self) -> List ``` The sum of the positive divisors of every `0..=n`, with `sigma[0] == 0`. - **cost**: O(n) - **order**: `sigma[k]` at key `k`, `k` in `0..=n`; a new `List` - **traps**: when a sum overflows `Int` Examples: - `Sieve(6).div_sum_table() == [0, 1, 3, 4, 7, 6, 12]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/math.cp#L327) ### `Sieve.divisors` ```cp fn divisors(self, x: Int) -> yields Int ``` The positive divisors of `x` in `1..=n`, built from the factorization, with no allocation. They come in mixed-radix order over the factorization: the exponent of the smallest prime changes fastest. That order is fixed but not sorted; use `.sorted()` for ascending. - **cost**: O(log x) to start, O(1) per divisor - **order**: mixed-radix over the exponents, smallest prime fastest (12 gives 1, 2, 4, 3, 6, 12) - **traps**: when `x` is outside `1..=n` Examples: - `Sieve(12).divisors(12).collect() == [1, 2, 4, 3, 6, 12]` - `Sieve(12).divisors(1).collect() == [1]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/math.cp#L355) ## `Sign` ```cp pub enum Sign ``` Which side of zero a number is on. `Int(s)` is -1, 0 or 1, so `x == Int(x.sign) * abs(x)`; `-s` flips it and `max(s, Sign.Zero)` clamps it. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/math.cp#L443) ### `Sign.Neg` ```cp Neg ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/math.cp#L443) ### `Sign.Zero` ```cp Zero ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/math.cp#L443) ### `Sign.Pos` ```cp Pos ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/math.cp#L443) ## `DirichletSum` ```cp pub struct DirichletSum ``` O(n^(2/3)) time and memory. Stateful Du's sieve cache for prefix sums of a multiplicative function `f` given prefix sums of `g` and `f * g`. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/math.cp#L1030) ### `DirichletSum.new` ```cp fn new(n: Int, f_small: List, g_sum: Int -> T, fg_sum: Int -> T) -> DirichletSum ``` A Du's-sieve cache for the prefix sums `F(m) = sum_{k=1..=m} f(k)` of a multiplicative `f`, up to `n`. `f_small[k]` is `f(k)` for `k` in `1..f_small.len` (index 0 ignored); sums up to there come from its prefix sums. Larger `m` use `g_sum(m) = sum_{k<=m} g(k)` and `fg_sum(m) = sum_{k<=m} (f * g)(k)` for a Dirichlet partner `g` with `g(1)` invertible: `F(m) = (fg_sum(m) - sum_{i=2..=m} g(i) F(m / i)) / g(1)`, grouped by floor quotients and memoized. A table of about `n^(2/3)` entries gives the stated cost. - **cost**: O(f_small.len) to build; queries as `sum` - **empty**: an empty `f_small` makes every query use the recursion - **traps**: when `n < 0` Examples: - `var ds = DirichletSum(10, [0, 1, 1, 2, 2], m => m, m => m * (m + 1) / 2); ds.sum(10) == 32` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/math.cp#L1046) ### `DirichletSum.sum` ```cp fn sum(mut self, m: Int) -> T ``` The prefix sum `F(m) = sum_{k=1..=m} f(k)`, with `F(0) == 0`. Results are memoized, so all the `n / i` values together cost O(n^(2/3)) when `f_small` has about `n^(2/3)` entries. - **cost**: O(1) cached; O(n^(2/3)) total across all `n / i` queries - **traps**: when `m` is outside `0..=n`, or `g(1)` is not invertible Examples: - `var ds = DirichletSum(10, [0, 1, 1, 2, 2, 4, 2, 6, 4, 6, 4], m => m, m => m * (m + 1) / 2); ds.sum(10) == 32` - `var ds = DirichletSum(10, [0, 1, 1, 2, 2], m => m, m => m * (m + 1) / 2); ds.sum(0) == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/math.cp#L1057) ## `Ratio` ```cp pub struct Ratio(p: Int, q: Int) ``` O(1) storage. Exact reduced rational `p / q` (`q > 0`, `gcd(|p|, q) == 1`). [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/math.cp#L1296) ### `Ratio.new` ```cp fn new(p: Int, q: Int = 1) -> Ratio ``` The fraction `p / q` in lowest terms, with a positive denominator. - **cost**: O(log min(|p|, |q|)) - **traps**: when `q == 0` Examples: - `Ratio(2, 4) == Ratio(1, 2)` - `Ratio(3, -6).floor == -1` - `Ratio(5) == Ratio.from_int(5)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/math.cp#L1304) ### `Ratio.from_int` ```cp fn from_int(n: Int) -> Ratio ``` `n` as the fraction `n / 1`. - **cost**: O(1) - **traps**: never Examples: - `Ratio.from_int(3) == Ratio(3, 1)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/math.cp#L1314) ### `Ratio.inv` ```cp fn inv(self) -> Ratio ``` The multiplicative inverse `q / p`, sign moved to the numerator. - **cost**: O(1) - **traps**: when `p == 0` Examples: - `Ratio(-2, 3).inv == Ratio(-3, 2)` - `Ratio(1, 4).inv == Ratio.from_int(4)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/math.cp#L1322) ### `Ratio.floor` ```cp fn floor(self) -> Int ``` The floor of `p / q` (Euclidean division). - **cost**: O(1) - **traps**: never Examples: - `Ratio(7, 2).floor == 3` - `Ratio(-7, 2).floor == -4` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/math.cp#L1330) ### `Ratio.ceil` ```cp fn ceil(self) -> Int ``` The ceiling of `p / q`: `ceil_div(p, q)`. - **cost**: O(1) - **traps**: never Examples: - `Ratio(7, 2).ceil == 4` - `Ratio(-7, 2).ceil == -3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/math.cp#L1338) ### `Ratio.abs` ```cp fn abs(self) -> Ratio ``` The absolute value `|p| / q`. - **cost**: O(1) - **traps**: never Examples: - `Ratio(-1, 2).abs == Ratio(1, 2)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/math.cp#L1345) ## `Ratio` ```cp impl Add for Ratio ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/math.cp#L1347) ### `Ratio.add` ```cp fn add(a, b) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/math.cp#L1348) ## `Ratio` ```cp impl Sub for Ratio ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/math.cp#L1350) ### `Ratio.sub` ```cp fn sub(a, b) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/math.cp#L1351) ## `Ratio` ```cp impl Neg for Ratio ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/math.cp#L1353) ### `Ratio.neg` ```cp fn neg(a) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/math.cp#L1354) ## `Ratio` ```cp impl Mul for Ratio ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/math.cp#L1356) ### `Ratio.mul` ```cp fn mul(a, b) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/math.cp#L1357) ## `Ratio` ```cp impl Div for Ratio ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/math.cp#L1359) ### `Ratio.div` ```cp fn div(a, b) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/math.cp#L1360) ## `Ratio` ```cp impl Ord for Ratio ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/math.cp#L1362) ### `Ratio.lt` ```cp fn lt(a, b) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/math.cp#L1363) ## `Ratio` ```cp impl Show for Ratio ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/math.cp#L1365) ### `Ratio.show` ```cp fn show(a) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/math.cp#L1366) ## `BigInt` ```cp pub struct BigInt(neg: Bool, limbs: List) ``` O(n) storage in base-10^9 limbs. Arbitrary-precision signed integer. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/math.cp#L1369) ### `BigInt.from_int` ```cp fn from_int(x: Int) -> BigInt ``` `x` as a `BigInt`. - **cost**: O(1) - **traps**: never Examples: - `BigInt.from_int(-42).to_str() == "-42"` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/math.cp#L1375) ### `BigInt.from_str` ```cp fn from_str(s: Str) -> BigInt ``` Parse a decimal integer: an optional leading `-`, then one or more digits. Leading zeros are allowed, and `-0` is zero. There is no `+` and no whitespace. - **cost**: O(s.len) - **traps**: when `s` is not an optional `-` followed by at least one decimal digit Examples: - `BigInt.from_str("-000123").to_str() == "-123"` - `BigInt.from_str("-0").to_str() == "0"` - `BigInt.from_str("123456789012345678901234567890").to_str() == "123456789012345678901234567890"` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/math.cp#L1386) ### `BigInt.to_str` ```cp fn to_str(self) -> Str ``` The decimal text of `self`: no leading zeros, a `-` only when negative, `"0"` for zero. - **cost**: O(n) - **traps**: never Examples: - `BigInt.from_int(0).to_str() == "0"` - `BigInt.from_int(-7).to_str() == "-7"` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/math.cp#L1394) ### `BigInt.divmod` ```cp fn divmod(self, d: BigInt) -> (BigInt, BigInt) ``` The Euclidean quotient and remainder `(self / d, self % d)`: `0 <= r < |d|`, as for `Int`. - **cost**: O(n * m) - **traps**: when `d` is zero Examples: - `BigInt.from_int(-7).divmod(BigInt.from_int(3)) == (BigInt.from_int(-3), BigInt.from_int(2))` - `BigInt.from_int(7).divmod(BigInt.from_int(-3)) == (BigInt.from_int(-2), BigInt.from_int(1))` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/math.cp#L1402) ### `BigInt.abs` ```cp fn abs(self) -> BigInt ``` The absolute value. - **cost**: O(n) - **traps**: never Examples: - `BigInt.from_int(-5).abs() == BigInt.from_int(5)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/math.cp#L1409) ### `BigInt.gcd` ```cp fn gcd(a: BigInt, b: BigInt) -> BigInt ``` The greatest common divisor of `a` and `b`, never negative; `gcd(0, 0)` is 0. - **cost**: O(n^2) - **traps**: never Examples: - `BigInt.gcd(BigInt.from_int(12), BigInt.from_int(-18)) == BigInt.from_int(6)` - `BigInt.gcd(BigInt.from_int(0), BigInt.from_int(0)) == BigInt.from_int(0)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/math.cp#L1417) ## `BigInt` ```cp impl Add for BigInt ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/math.cp#L1419) ### `BigInt.add` ```cp fn add(a, b) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/math.cp#L1420) ## `BigInt` ```cp impl Sub for BigInt ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/math.cp#L1422) ### `BigInt.sub` ```cp fn sub(a, b) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/math.cp#L1423) ## `BigInt` ```cp impl Neg for BigInt ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/math.cp#L1425) ### `BigInt.neg` ```cp fn neg(a) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/math.cp#L1426) ## `BigInt` ```cp impl Mul for BigInt ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/math.cp#L1428) ### `BigInt.mul` ```cp fn mul(a, b) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/math.cp#L1429) ## `BigInt` ```cp impl Div for BigInt ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/math.cp#L1431) ### `BigInt.div` ```cp fn div(a, b) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/math.cp#L1432) ## `BigInt` ```cp impl Ord for BigInt ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/math.cp#L1434) ### `BigInt.lt` ```cp fn lt(a, b) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/math.cp#L1435) ## `BigInt` ```cp impl Show for BigInt ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/math.cp#L1437) ### `BigInt.show` ```cp fn show(a) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/math.cp#L1438) ## `inf` ```cp pub const inf: Int = 9_223_372_036_854_775_807 ``` `Int.MAX`, for `Int` tables that start "unreached" when `?Int` with `None` is not wanted. `min` treats it as its identity; adding to it overflows (a trap in checked builds). [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/math.cp#L1674) --- # matrix URL: /docs/ref/std/matrix Generated from [spec/std/matrix.cp](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/matrix.cp) by `cpl doc --format json`. ## `Mat` ```cp pub struct Mat ``` A dense `rows x cols` matrix stored flat in row-major order. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/matrix.cp#L13) ### `Mat.new` ```cp fn new(a: [R, C]T, over: ?S = None) -> Mat ``` A matrix from a 2-D table, multiplied under `over` (default `Semiring(+, *)`): `Mat(over: Semiring(min, +), d)`. `m * m2`, `pow(m, k)` and a `SegTree(*, ...)` of matrices all use it. O(rows * cols). Row `i` is `R`'s `i`-th position and column `j` is `C`'s `j`-th, so `get(i, j)` reads `a[R.nth(i), C.nth(j)]`; the matrix has `|R|` rows and `|C|` columns. The keys are not kept. - **cost**: O(rows * cols) time and space - **empty**: a matrix with zero rows or columns - **traps**: never Examples: - `domain R = 0..2; domain C = 0..3; Mat([R, C] (r, c) => 10 * Int(r) + Int(c)).get(1, 2) == 12` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/matrix.cp#L29) ### `Mat.filled` ```cp fn filled(rows: Int, cols: Int, fill: T, over: ?S = None) -> Mat ``` A `rows x cols` matrix with every entry `fill`, multiplied under `over` (default `Semiring(+, *)`). - **cost**: O(rows * cols) time and space - **traps**: when `rows < 0` or `cols < 0` Examples: - `Mat.filled(2, 3, 7).get(1, 2) == 7` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/matrix.cp#L37) ### `Mat.zeros` ```cp fn zeros(rows: Int, cols: Int) -> Mat ``` A `rows x cols` matrix of `T.zero`. - **cost**: O(rows * cols) time and space - **traps**: when `rows < 0` or `cols < 0` Examples: - `Mat.zeros(2, 3).get(1, 2) == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/matrix.cp#L44) ### `Mat.identity` ```cp fn identity(n: Int) -> Mat ``` The `n x n` identity matrix: `T.one` on the diagonal, `T.zero` elsewhere. - **cost**: O(n^2) time and space - **traps**: when `n < 0` Examples: - `let m = Mat.identity(3); m.get(1, 1) == 1 and m.get(1, 2) == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/matrix.cp#L53) ### `Mat.from_flat` ```cp fn from_flat(rows: Int, cols: Int, data: List) -> Mat ``` Build a `rows x cols` matrix from a flat row-major list of length `rows * cols`: entry `(r, c)` is `data[r * cols + c]`. - **cost**: O(rows * cols) time and space - **empty**: a matrix with zero rows or columns when `data` is empty - **traps**: when `rows < 0`, `cols < 0` or `data.len != rows * cols` Examples: - `Mat.from_flat(2, 3, [1, 2, 3, 4, 5, 6]).get(1, 0) == 4` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/matrix.cp#L66) ### `Mat.from_rows` ```cp fn from_rows(grid: List>) -> Mat ``` Build a matrix from a list of equal-length rows: `grid[r][c]` is entry `(r, c)`. - **cost**: O(rows * cols) time and space - **empty**: `[]` gives the `0 x 0` matrix - **traps**: when the rows differ in length Examples: - `Mat.from_rows([[1, 2], [3, 4]]).get(1, 0) == 3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/matrix.cp#L76) ### `Mat.get` ```cp fn get(self, r: Int, c: Int) -> T ``` The entry at `(r, c)`, 0-based. - **cost**: O(1) - **traps**: when `r` is not in `0..rows` or `c` is not in `0..cols` Examples: - `Mat.from_rows([[1, 2], [3, 4]]).get(0, 1) == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/matrix.cp#L91) ### `Mat.set` ```cp fn set(mut self, r: Int, c: Int, val: T) ``` Set the entry at `(r, c)` to `val`. - **cost**: O(1) - **traps**: when `r` is not in `0..rows` or `c` is not in `0..cols` Examples: - `var m = Mat.zeros(2, 2); m.set(1, 0, 5); m.get(1, 0) == 5` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/matrix.cp#L98) ### `Mat.at` ```cp fn at(self, r: Int, c: Int) -> lends mut T ``` The entry at `(r, c)`, lent in place: `m.at(i, j) += x`. - **cost**: O(1) - **traps**: when `r` is not in `0..rows` or `c` is not in `0..cols` Examples: - `var m = Mat.identity(2); m.at(0, 0) += 4; m.get(0, 0) == 5` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/matrix.cp#L106) ### `Mat.transpose` ```cp fn transpose(self) -> Mat ``` The transpose, a new `cols x rows` matrix with entry `(c, r)` equal to `self`'s `(r, c)`. - **cost**: O(rows * cols) time and space - **traps**: never Examples: - `Mat.from_rows([[1, 2, 3], [4, 5, 6]]).transpose().get(2, 1) == 6` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/matrix.cp#L114) ### `Mat.mul_vec` ```cp fn mul_vec(self, v: List) -> List ``` The matrix-vector product `self * v` under the matrix's semiring: entry `r` folds `get(r, c) * v[c]` over `c` with the semiring's addition. - **cost**: O(rows * cols) time, O(rows) space - **empty**: `rows` copies of the semiring's zero when `cols == 0` - **order**: indexed by row - **traps**: when `v.len != cols` Examples: - `Mat.from_rows([[1, 2], [3, 4]]).mul_vec([1, 1]) == [3, 7]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/matrix.cp#L128) ### `Mat.product` ```cp fn product(n: Int) -> Monoid> ``` The matrix-multiplication monoid for `n x n` matrices (usable in `SegTree`): identity `Mat.identity(n)`, op `*`, which is associative but not commutative. - **cost**: O(n^2) time and space (for the identity) - **traps**: when `n < 0` Examples: - `let m = Mat.product(2); m.op(m.id, Mat.from_rows([[1, 2], [3, 4]])).get(1, 1) == 4` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/matrix.cp#L144) ### `Mat.det` ```cp fn det(self) -> T ``` The determinant over an exact field (such as `Mod

` for prime `P`), by Gaussian elimination. The `0 x 0` determinant is `T.one`. - **cost**: O(n^3) time, O(n^2) space - **traps**: when the matrix is not square, or an inverse it needs does not exist (a non-field `T`) Examples: - `Mat>.from_rows([[1, 2], [3, 4]]).det() == Mod<7>(5)` - `Mat>.from_rows([[1, 2], [2, 4]]).det() == Mod<7>(0)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/matrix.cp#L153) ### `Mat.rank` ```cp fn rank(self) -> Int ``` The rank over an exact field: the number of pivots elimination finds. - **cost**: O(rows * cols * min(rows, cols)) time, O(rows * cols) space - **empty**: zero - **traps**: never for a field `T` Examples: - `Mat>.from_rows([[1, 2], [2, 4]]).rank() == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/matrix.cp#L181) ### `Mat.solve_space` ```cp fn solve_space(self, b: List) -> ?(List, List>) ``` Solve `self * x = b` over an exact field. Returns `(particular, nullspace_basis)` or `None`. Every solution has the form `particular + sum(c_i * basis[i])`. O(rows * cols * min(rows, cols)). `particular` is the solution with every free variable zero (what `solve` returns). The basis has one vector per free (non-pivot) column of the reduced row echelon form, in increasing column order; the vector for free column `f` has `1` at `f`, `0` at the other free columns, and whatever the pivot columns need. It is empty when the solution is unique. - **cost**: O(rows * cols * min(rows, cols)) time, O(rows * cols) space - **empty**: with `cols == 0`, `Some(([], []))` when `b` is all zero, else `None` - **order**: basis vectors by increasing free column - **traps**: when `b.len != rows` Examples: - `Mat>.from_rows([[1, 2], [2, 4]]).solve_space([1, 2]) == Some(([Mod<7>(1), Mod<7>(0)], [[Mod<7>(5), Mod<7>(1)]]))` - `Mat>.from_rows([[1, 2], [2, 4]]).solve_space([1, 0]) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/matrix.cp#L214) ### `Mat.solve` ```cp fn solve(self, b: List) -> ?List ``` Solve `self * x = b` over an exact field. Returns one solution (free variables 0) or `None`. The solution is `solve_space(b)`'s particular one: each free (non-pivot) column's variable is zero. - **cost**: O(rows * cols * min(rows, cols)) time, O(rows * cols) space - **empty**: with `cols == 0`, `Some([])` when `b` is all zero, else `None` - **order**: indexed by column (variable) - **traps**: when `b.len != rows` Examples: - `Mat>.from_rows([[1, 2], [3, 4]]).solve([5, 6]) == Some([Mod<7>(3), Mod<7>(1)])` - `Mat>.from_rows([[1, 2], [2, 4]]).solve([1, 0]) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/matrix.cp#L266) ### `Mat.inverse` ```cp fn inverse(self) -> ?Mat ``` The multiplicative inverse of a square matrix over an exact field, or `None` if singular, by Gauss-Jordan elimination. - **cost**: O(n^3) time, O(n^2) space - **empty**: the `0 x 0` matrix is its own inverse - **traps**: when the matrix is not square Examples: - `let inv = Mat>.from_rows([[1, 2], [3, 4]]).inverse()!; inv.get(0, 0) == Mod<7>(5) and inv.get(1, 1) == Mod<7>(3)` - `Mat>.from_rows([[1, 2], [2, 4]]).inverse() == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/matrix.cp#L279) ### `Mat.rref` ```cp fn rref(self) -> (mat: Mat, rank: Int, pivots: List) ``` The reduced row echelon form `(rref_mat, rank, pivot_cols)` over a field. Every pivot is `T.one`, every other entry of a pivot column is zero, the nonzero rows come first, and the `rank` pivot columns are listed in increasing order. The RREF is unique, so so is the result. - **cost**: O(rows * cols * min(rows, cols)) time, O(rows * cols) space - **empty**: rank zero, no pivots - **order**: pivot columns increasing - **traps**: never for a field `T` Examples: - `let (mat: e, rank: k, pivots: p) = Mat>.from_rows([[2, 4], [1, 2]]).rref(); k == 1 and p == [0] and e.get(0, 1) == Mod<7>(2) and e.get(1, 1) == Mod<7>(0)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/matrix.cp#L314) ### `Mat.det_mod` ```cp fn det_mod(self, m: Int) -> Int ``` The determinant modulo any (possibly composite) `m >= 1`, in `0..m`, by Euclidean (gcd-style) row elimination, so no inverse is needed. Entries are reduced modulo `m` first, negative ones included. - **cost**: O(n^3 log m) - **empty**: `1 % m` for the `0 x 0` matrix - **traps**: when the matrix is not square or `m < 1` Examples: - `Mat.from_rows([[1, 2], [3, 4]]).det_mod(6) == 4` - `Mat.from_rows([[2, 0], [0, 3]]).det_mod(6) == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/matrix.cp#L345) ### `Mat.char_poly` ```cp fn char_poly(self) -> List ``` The characteristic polynomial `det(xI - self)`, lowest degree first, via Hessenberg reduction: `n + 1` coefficients, the last one `T.one`. - **cost**: O(n^3) time, O(n^2) space - **empty**: `[T.one]` for the `0 x 0` matrix - **order**: coefficient of `x^0` first - **traps**: when the matrix is not square Examples: - `Mat>.from_rows([[1, 2], [3, 4]]).char_poly() == [Mod<7>(5), Mod<7>(2), Mod<7>(1)]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/matrix.cp#L371) ### `Mat.pfaffian` ```cp fn pfaffian(self) -> T ``` The Pfaffian of an even-order skew-symmetric matrix over a field, with the sign convention `pf([[0, a], [-a, 0]]) == a`; `pf(A)^2 == det(A)`. Only the entries above the diagonal are read; skew-symmetry is not checked. - **cost**: O(n^3) time, O(n^2) space - **empty**: `T.one` for the `0 x 0` matrix - **traps**: when the matrix is not square or `n` is odd Examples: - `Mat>.from_rows([[0, 3], [4, 0]]).pfaffian() == Mod<7>(3)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/matrix.cp#L414) ### `Mat.adjugate` ```cp fn adjugate(self) -> Mat ``` The adjugate matrix `adj(self)`, the transpose of the cofactor matrix, so `self * adj(self) == det(self) * I`. Defined even when `rank == n - 1` (and zero when `rank < n - 1`). - **cost**: O(n^3) time, O(n^2) space - **empty**: the `0 x 0` matrix - **traps**: when the matrix is not square Examples: - `let a = Mat>.from_rows([[1, 2], [3, 4]]).adjugate(); a.get(0, 0) == Mod<7>(4) and a.get(0, 1) == Mod<7>(5)` - `Mat>.from_rows([[5]]).adjugate().get(0, 0) == Mod<7>(1)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/matrix.cp#L457) ## `Mat` ```cp impl Add for Mat ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/matrix.cp#L488) ### `Mat.add` ```cp fn add(a, b) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/matrix.cp#L489) ## `Mat` ```cp impl Sub for Mat ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/matrix.cp#L493) ### `Mat.sub` ```cp fn sub(a, b) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/matrix.cp#L494) ## `Mat` ```cp impl Mul for Mat ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/matrix.cp#L498) ### `Mat.mul` ```cp fn mul(a, b) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/matrix.cp#L499) ## `Mat` ```cp impl Pow for Mat ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/matrix.cp#L513) ### `Mat.pow` ```cp fn pow(a, e: Int) -> Mat ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/matrix.cp#L514) ## `XorBasis` ```cp pub struct XorBasis ``` Linear basis over GF(2) for non-negative 63-bit integers (`0 <= x < 2^63`). Every operation is O(W) where W <= 63 (`merge` is O(W * rank)). [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/matrix.cp#L662) ### `XorBasis.new` ```cp fn new() -> XorBasis ``` An empty basis of rank 0, whose span is `{0}`. - **cost**: O(W) - **traps**: never Examples: - `XorBasis().rank == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/matrix.cp#L671) ### `XorBasis.rank` ```cp fn rank(self) -> Int ``` The number of linearly independent vectors in the basis: the span has `2^rank` elements. - **cost**: O(1) - **traps**: never Examples: - `var b = XorBasis(); b.add(6); b.add(5); b.add(3); b.rank == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/matrix.cp#L678) ### `XorBasis.add` ```cp fn add(mut self, x: Int) -> Bool ``` Insert `x >= 0` into the basis. Returns `true` iff the rank increased, that is, iff `x` was not already in the span (`0` never is new). The basis is kept fully reduced: no vector has another vector's highest bit set. - **cost**: O(W) - **traps**: when `x < 0` Examples: - `var b = XorBasis(); let p = b.add(6); let q = b.add(5); let r = b.add(3); p and q and not r` - `not XorBasis().add(0)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/matrix.cp#L688) ### `XorBasis.reduce` ```cp fn reduce(self, x: Int) -> Int ``` Reduce `x >= 0` against the basis: the minimum of `x ^ s` over `s` in the span, which is 0 iff `x` is in the span. - **cost**: O(W) - **traps**: when `x < 0` Examples: - `var b = XorBasis(); b.add(6); b.add(5); b.reduce(4) == 1 and b.reduce(3) == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/matrix.cp#L708) ### `XorBasis.contains` ```cp fn contains(self, x: Int) -> Bool ``` Whether `x >= 0` is a XOR-combination of basis vectors: `reduce(x) == 0`. - **cost**: O(W) - **traps**: when `x < 0` Examples: - `var b = XorBasis(); b.add(6); b.add(5); b.contains(3) and not b.contains(4)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/matrix.cp#L722) ### `XorBasis.max_xor` ```cp fn max_xor(self, init: Int = 0) -> Int ``` The maximum value of `init ^ s` over all `s` in the span. - **cost**: O(W) - **ties**: None possible; the maximum value is unique - **traps**: when `init < 0` Examples: - `var b = XorBasis(); b.add(6); b.add(5); b.max_xor() == 6 and b.max_xor(1) == 7` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/matrix.cp#L730) ### `XorBasis.min_xor` ```cp fn min_xor(self, init: Int = 0) -> Int ``` The minimum value of `init ^ s` over all `s` in the span: the same as `reduce(init)`, and 0 for the default `init`. - **cost**: O(W) - **ties**: None possible; the minimum value is unique - **traps**: when `init < 0` Examples: - `var b = XorBasis(); b.add(6); b.add(5); b.min_xor(4) == 1 and b.min_xor() == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/matrix.cp#L746) ### `XorBasis.kth` ```cp fn kth(self, k: Int) -> ?Int ``` The 0-indexed `k`-th smallest value in the span, or `None` if `k < 0` or `k >= 2^rank`. `kth(0)` is 0, and `kth` over `0..2^rank` is strictly increasing and lists the whole span. - **cost**: O(W^2) - **empty**: only `kth(0) == Some(0)` for an empty basis - **ties**: None possible; span values are distinct - **traps**: never Examples: - `var b = XorBasis(); b.add(6); b.add(5); [b.kth(k) for k in 0..5] == [Some(0), Some(3), Some(5), Some(6), None]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/matrix.cp#L763) ### `XorBasis.merge` ```cp fn merge(mut self, o: XorBasis) ``` Merge another basis into `self`, so `self` spans the union of both spans; `o` is unchanged. - **cost**: O(W * o.rank) - **traps**: never Examples: - `var a = XorBasis(); a.add(6); var b = XorBasis(); b.add(8); a.merge(b); a.rank == 2 and a.contains(14)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/matrix.cp#L784) ### `XorBasis.monoid` ```cp fn monoid() -> Monoid ``` The monoid under basis merge (usable in `SegTree`): identity the empty basis, op the merged basis. Commutative and idempotent on spans. - **cost**: O(W) (for the identity) - **traps**: never Examples: - `let m = XorBasis.monoid(); m.id.rank == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/matrix.cp#L795) ### `XorBasis.basis_vecs` ```cp fn basis_vecs(self) -> List ``` The independent basis vectors currently stored, fully reduced (no vector has another's highest bit set), so the list depends only on the span. One vector per rank. - **cost**: O(W) time and space - **empty**: `[]` - **order**: decreasing (by highest set bit) - **traps**: never Examples: - `var b = XorBasis(); b.add(6); b.add(5); b.basis_vecs() == [5, 3]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/matrix.cp#L805) ### `XorBasis.intersect` ```cp fn intersect(self, o: XorBasis) -> XorBasis ``` A new basis spanning the intersection of the two GF(2) vector subspaces. - **cost**: O(W^2) - **traps**: never Examples: - `var a = XorBasis(); a.add(6); a.add(5); var b = XorBasis(); b.add(3); b.add(8); let c = a.intersect(b); c.rank == 1 and c.contains(3)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/matrix.cp#L822) ## `MatPow` ```cp pub struct MatPow ``` O(n^3 log max_exp) build, O(n^2 log e) query. Precomputed binary powers of a square matrix for fast multi-query `A^e * v`. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/matrix.cp#L857) ### `MatPow.new` ```cp fn new(a: Mat, max_exp: Int) -> MatPow ``` Precompute `a^(2^k)` for every `k` with `2^k <= max_exp`, multiplied under `a`'s semiring. - **cost**: O(n^3 log max_exp) time, O(n^2 log max_exp) space - **traps**: when `a` is not square or `max_exp < 0` Examples: - `let p = MatPow(Mat.from_rows([[1, 1], [1, 0]]), 10); p.apply_pow(5, [1, 0]) == [8, 5]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/matrix.cp#L866) ### `MatPow.apply_pow` ```cp fn apply_pow(self, e: Int, v: List) -> List ``` Compute `a^e * v` for `0 <= e <= max_exp`, as matrix-vector products with the stored powers for the set bits of `e`. `e == 0` returns `v`. - **cost**: O(n^2 log e) time, O(n) space - **empty**: `v` itself when `e == 0` - **order**: indexed by row - **traps**: when `e` is not in `0..=max_exp` or `v.len != n` Examples: - `let p = MatPow(Mat.from_rows([[1, 1], [1, 0]]), 10); p.apply_pow(0, [1, 0]) == [1, 0]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/matrix.cp#L885) ## `BitMat` ```cp pub struct BitMat(rows: Int, cols: Int) ``` O(n * m / 64) storage. Bit-packed dense matrix over GF(2) with word-parallel elimination. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/matrix.cp#L893) ### `BitMat.new` ```cp fn new(rows: Int, cols: Int) -> BitMat ``` A zero GF(2) matrix of `rows x cols`, one bit per entry. - **cost**: O(rows * cols / 64) time and space - **traps**: when `rows < 0` or `cols < 0` Examples: - `BitMat(2, 3).rank() == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/matrix.cp#L901) ### `BitMat.identity` ```cp fn identity(n: Int) -> BitMat ``` The `n x n` GF(2) identity matrix. - **cost**: O(n^2 / 64) time and space - **traps**: when `n < 0` Examples: - `BitMat.identity(3).get(1, 1) and not BitMat.identity(3).get(1, 2)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/matrix.cp#L910) ### `BitMat.get` ```cp fn get(self, r: Int, c: Int) -> Bool ``` Read bit `(r, c)`. - **cost**: O(1) - **traps**: when `r` is not in `0..rows` or `c` is not in `0..cols` Examples: - `var m = BitMat(2, 2); m.set(0, 1, true); m.get(0, 1) and not m.get(1, 0)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/matrix.cp#L920) ### `BitMat.set` ```cp fn set(mut self, r: Int, c: Int, v: Bool) ``` Write bit `(r, c)`. - **cost**: O(1) - **traps**: when `r` is not in `0..rows` or `c` is not in `0..cols` Examples: - `var m = BitMat(2, 2); m.set(0, 1, true); m.set(0, 1, false); not m.get(0, 1)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/matrix.cp#L929) ### `BitMat.det` ```cp fn det(self) -> Bool ``` The determinant over GF(2): `true` iff the matrix is invertible. The `0 x 0` determinant is `true`. - **cost**: O(n^3 / 64) - **traps**: when the matrix is not square Examples: - `var m = BitMat.identity(2); m.set(0, 1, true); m.det()` - `var m = BitMat(2, 2); m.set(0, 0, true); m.set(1, 0, true); not m.det()` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/matrix.cp#L943) ### `BitMat.rank` ```cp fn rank(self) -> Int ``` The rank over GF(2). - **cost**: O(rows * cols * min(rows, cols) / 64) - **empty**: zero - **traps**: never Examples: - `var m = BitMat(2, 2); m.set(0, 0, true); m.set(0, 1, true); m.set(1, 0, true); m.set(1, 1, true); m.rank() == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/matrix.cp#L953) ### `BitMat.solve` ```cp fn solve(self, b: List) -> ?List ``` Any solution to `self * x == b` over GF(2), or `None`: the one with every free (non-pivot) variable `false`, as in `Mat.solve`. - **cost**: O(rows * cols * min(rows, cols) / 64) - **empty**: with `cols == 0`, `Some([])` when `b` is all `false`, else `None` - **order**: indexed by column (variable) - **traps**: when `b.len != rows` Examples: - `var m = BitMat.identity(2); m.set(0, 1, true); m.solve([true, true]) == Some([false, true])` - `var m = BitMat(2, 2); m.set(0, 0, true); m.set(0, 1, true); m.set(1, 0, true); m.set(1, 1, true); m.solve([true, false]) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/matrix.cp#L966) ### `BitMat.solve_space` ```cp fn solve_space(self, b: List) -> ?(x0: List, basis: List>) ``` One solution `x0` and a nullspace basis over GF(2), or `None`. `x0` is `solve(b)`'s solution; the basis has one vector per free column, in increasing column order, with `true` at that column and `false` at the other free columns, as in `Mat.solve_space`. - **cost**: O(rows * cols * min(rows, cols) / 64) - **empty**: with `cols == 0`, `Some(([], []))` when `b` is all `false`, else `None` - **order**: basis vectors by increasing free column - **traps**: when `b.len != rows` Examples: - `var m = BitMat(2, 2); m.set(0, 0, true); m.set(0, 1, true); m.set(1, 0, true); m.set(1, 1, true); m.solve_space([true, true]) == Some((x0: [true, false], basis: [[true, true]]))` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/matrix.cp#L979) ### `BitMat.inverse` ```cp fn inverse(self) -> ?BitMat ``` The inverse of a square GF(2) matrix, or `None` when it is singular. - **cost**: O(n^3 / 64) - **empty**: the `0 x 0` matrix - **traps**: when the matrix is not square Examples: - `var m = BitMat.identity(2); m.set(0, 1, true); let inv = m.inverse()!; inv.get(0, 1) and inv.get(1, 1) and not inv.get(1, 0)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/matrix.cp#L1008) ### `BitMat.mul` ```cp fn mul(self, o: BitMat) -> BitMat ``` The matrix product `self * o` over GF(2) (AND for multiply, XOR for add). - **cost**: O(rows * cols * o.cols / 64) - **traps**: when `self.cols != o.rows` Examples: - `var m = BitMat.identity(2); m.set(0, 1, true); let p = m.mul(m); not p.get(0, 1) and p.get(0, 0)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/matrix.cp#L1029) ## `PrefixXorBasis` ```cp pub struct PrefixXorBasis ``` O(62) per push and query. Online prefix linear basis answering subarray XOR queries over any range `r`. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/matrix.cp#L1062) ### `PrefixXorBasis.new` ```cp fn new() -> PrefixXorBasis ``` An empty prefix XOR basis, with no positions pushed. - **cost**: O(1) - **traps**: never Examples: - `PrefixXorBasis().rank(0..0) == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/matrix.cp#L1072) ### `PrefixXorBasis.push` ```cp fn push(mut self, x: Int) ``` Append `x` at the next position (`0`, `1`, ...), keeping for each bit the basis vector with the rightmost source index, so any subarray's span reads off the vectors whose index lies in it. - **cost**: O(62) time and space - **traps**: when `x < 0` or `x >= 2^62` Examples: - `var p = PrefixXorBasis(); p.push(6); p.push(5); p.rank(0..2) == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/matrix.cp#L1080) ### `PrefixXorBasis.max_xor` ```cp fn max_xor(self, r: Range, init: Int = 0) -> Int ``` The maximum `init ^ s` for `s` in the span of the values at positions `r`. - **cost**: O(62) - **empty**: `init` (the span of nothing is `{0}`) - **ties**: None possible; the maximum value is unique - **traps**: when `r` is non-empty and reaches outside `0..len`, or `init < 0` Examples: - `var p = PrefixXorBasis(); p.push(6); p.push(5); p.push(3); p.max_xor(1..3) == 6 and p.max_xor(2..3) == 3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/matrix.cp#L1112) ### `PrefixXorBasis.contains` ```cp fn contains(self, r: Range, x: Int) -> Bool ``` Whether `x` is in the span of the values at positions `r`. - **cost**: O(62) - **empty**: `true` only for `x == 0` - **traps**: when `r` is non-empty and reaches outside `0..len`, or `x < 0` Examples: - `var p = PrefixXorBasis(); p.push(6); p.push(5); p.push(3); p.contains(1..3, 6) and not p.contains(1..2, 3)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/matrix.cp#L1127) ### `PrefixXorBasis.rank` ```cp fn rank(self, r: Range) -> Int ``` The rank (dimension) of the span of the values at positions `r`. - **cost**: O(62) - **empty**: zero - **traps**: when `r` is non-empty and reaches outside `0..len` Examples: - `var p = PrefixXorBasis(); p.push(6); p.push(5); p.push(3); p.rank(0..3) == 2 and p.rank(2..3) == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/matrix.cp#L1142) --- # mod URL: /docs/ref/std/mod Generated from [spec/std/mod.cp](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/mod.cp) by `cpl doc --format json`. ## `Mod` ```cp pub struct Mod

(v: 0..P) ``` An integer modulo the constant `P`, always stored in `0..P`. `+ - *` are O(1); `/` and `inv` are O(log P) and need `gcd(x, P) == 1`. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/mod.cp#L15) ### `Mod.MOD` ```cp let MOD ``` The modulus: `Z.MOD`. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/mod.cp#L17) ### `Mod.new` ```cp fn new(x: Int) -> Mod

``` Any `Int`, reduced into `0..P` by Euclidean remainder: `Mod<7>(-1)` is 6. `Mod

(x)` calls `new`, so every way of building a `Mod` reduces. - **cost**: O(1) - **traps**: never Examples: - `Mod<7>(-1) == Mod<7>(6)` - `Mod<7>(15) == Mod<7>(1)` - `Mod<1>(5) == Mod<1>(0)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/mod.cp#L30) ### `Mod.try_inv` ```cp fn try_inv(self) -> ?Mod

``` The multiplicative inverse when `gcd(v, P) == 1`, or `None` otherwise. Uses the extended Euclidean algorithm, so `P` need not be prime. With `P == 1` the only value is 0, which is also `one`, so `Mod<1>(0).try_inv()` is `Some(Mod<1>(0))`. - **cost**: O(log P) - **traps**: never Examples: - `Mod<7>(3).try_inv() == Some(Mod<7>(5))` - `Mod<6>(4).try_inv() == None` - `Mod<7>(0).try_inv() == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/mod.cp#L42) ### `Mod.inv` ```cp fn inv(self) -> Mod

``` The multiplicative inverse, by the extended Euclidean algorithm (so `P` need not be prime). `x.inv()` is `x.try_inv().unwrap()` with a trap that names `x` and `P`; `a / b` is `a * b.inv()`. - **cost**: O(log P) - **traps**: when `gcd(v, P) != 1` Examples: - `Mod<7>(3).inv() == Mod<7>(5)` - `Mod<10>(3).inv() == Mod<10>(7)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/mod.cp#L60) ### `Mod.from_int` ```cp fn from_int(x: Int) -> Mod

``` Lift an `Int` to `Mod

`; the same reduction as `new`. This is the conversion an `Int` literal takes where a `Mod

` is expected, so `let x: Mod<7> = 10` is `Mod<7>.from_int(10)`. - **cost**: O(1) - **traps**: never Examples: - `Mod<7>.from_int(10) == Mod<7>(3)` - `Mod<7>.from_int(-8) == Mod<7>(6)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/mod.cp#L71) ### `Mod.sqrt` ```cp fn sqrt(self) -> ?Mod

``` A square root modulo the prime `P` (Tonelli-Shanks), or `None` when there is None. Of the two roots `r` and `P - r`, it returns the one with the smaller value `v`; the root of 0 is 0. - **cost**: O(log^2 P) - **ties**: the root with the smaller value - **traps**: when `P` is not prime Examples: - `Mod<7>(2).sqrt() == Some(Mod<7>(3))` - `Mod<7>(3).sqrt() == None` - `Mod<7>(0).sqrt() == Some(Mod<7>(0))` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/mod.cp#L84) ### `Mod.log` ```cp fn log(self, target: Mod

) -> ?Int ``` The least `k >= 0` with `self ** k == target` (baby-step giant-step), or `None`. Any modulus works: the non-coprime part is peeled off first. `self ** 0` is `one`, so `x.log(one)` is `Some(0)` for every `x`. - **cost**: O(sqrt P) - **ties**: the least `k` - **traps**: never Examples: - `Mod<7>(3).log(Mod<7>(6)) == Some(3)` - `Mod<7>(3).log(Mod<7>(1)) == Some(0)` - `Mod<7>(2).log(Mod<7>(3)) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/mod.cp#L99) ### `Mod.inv_all` ```cp fn inv_all(xs: List>) -> List> ``` The inverse of every element of `xs`, with one `inv` in all (Montgomery's trick). - **cost**: O(n + log P) - **empty**: `[]` - **order**: same order as `xs`; a new `List`, keyed from 0 - **traps**: when any element has `gcd(v, P) != 1` (in particular 0) Examples: - `Mod<7>.inv_all([Mod<7>(1), Mod<7>(2), Mod<7>(3)]) == [Mod<7>(1), Mod<7>(4), Mod<7>(5)]` - `let e: List> = []; Mod<7>.inv_all(e) == []` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/mod.cp#L109) ## `Mod

` ```cp impl Add for Mod

``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/mod.cp#L121) ### `Mod

.add` ```cp fn add(a, b) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/mod.cp#L122) ## `Mod

` ```cp impl Sub for Mod

``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/mod.cp#L124) ### `Mod

.sub` ```cp fn sub(a, b) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/mod.cp#L125) ## `Mod

` ```cp impl Neg for Mod

``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/mod.cp#L127) ### `Mod

.neg` ```cp fn neg(a) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/mod.cp#L128) ## `Mod

` ```cp impl Mul for Mod

``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/mod.cp#L130) ### `Mod

.mul` ```cp fn mul(a, b) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/mod.cp#L133) ## `Mod

` ```cp impl Div for Mod

``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/mod.cp#L135) ### `Mod

.div` ```cp fn div(a, b) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/mod.cp#L136) ## `Mod

` ```cp impl Pow for Mod

``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/mod.cp#L138) ### `Mod

.pow` ```cp fn pow(a, e: Int) -> Mod

``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/mod.cp#L139) ## `Mod

` ```cp impl Show for Mod

``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/mod.cp#L148) ### `Mod

.show` ```cp fn show(a) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/mod.cp#L149) ## `Mod

` ```cp impl Read for Mod

``` One signed integer token of any length, reduced modulo `P`, so a 10^4-digit coefficient is `read>()`. (R10.2.3) [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/mod.cp#L153) ### `Mod

.read` ```cp fn read() -> Mod

``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/mod.cp#L154) ## `Comb` ```cp pub struct Comb ``` Factorials and inverse factorials for a modular type `M = Mod

` (prime `P`). Its tables are `@cache` fields that grow on demand, so an immutable `let c = Comb()` (or `Comb(limit)` to pre-size) answers queries in O(1) with amortized O(1) growth per new factorial. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/mod.cp#L167) ### `Comb.new` ```cp fn new(limit: Int = 0) -> Comb ``` Precompute factorials and inverse factorials up to `limit` for `M = Mod

`, `P` prime. The tables hold `min(limit, P - 1) + 1` entries and grow on demand later (doubling, capped at `P`), so `Comb()` with no limit is valid and simply grows on first use. - **cost**: O(min(limit, P)) - **traps**: when `limit < 0`, or `P` is not prime Examples: - `type Z = Mod<7>; let c = Comb(3); c.fact(3) == Z(6)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/mod.cp#L180) ### `Comb.grow` ```cp fn grow(self, want: Int) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/mod.cp#L191) ### `Comb.ensure` ```cp fn ensure(self, n: Int) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/mod.cp#L201) ### `Comb.fact` ```cp fn fact(self, n: Int) -> M ``` `n!`, reduced; 0 when `n >= M.MOD` (the product contains `P`). - **cost**: O(1) amortized - **traps**: when `n < 0` Examples: - `type Z = Mod<1_000_000_007>; Comb().fact(5) == Z(120)` - `type Z = Mod<7>; Comb().fact(6) == Z(6)` - `type Z = Mod<7>; Comb().fact(7) == Z(0)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/mod.cp#L211) ### `Comb.inv_fact` ```cp fn inv_fact(self, n: Int) -> M ``` `1 / n!`, for `0 <= n < M.MOD`. - **cost**: O(1) amortized - **traps**: when `n` is outside `0..M.MOD` Examples: - `type Z = Mod<7>; Comb().inv_fact(3) == Z(6)` - `type Z = Mod<7>; Comb().inv_fact(0) == Z(1)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/mod.cp#L223) ### `Comb.inv` ```cp fn inv(self, i: Int) -> M ``` `1 / i`, for `1 <= i < M.MOD`, from the factorials: `(i - 1)! / i!`. - **cost**: O(1) amortized - **traps**: when `i` is outside `1..M.MOD` Examples: - `type Z = Mod<7>; Comb().inv(3) == Z(5)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/mod.cp#L233) ### `Comb.choose_lucas` ```cp fn choose_lucas(self, n: Int, k: Int) -> M ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/mod.cp#L238) ### `Comb.choose` ```cp fn choose(self, n: Int, k: Int) -> M ``` The number of `k`-subsets of `n` things, `n! / (k! (n - k)!)`; 0 when `k` is outside `0..=n`. For `n < M.MOD` it reads the tables. For `n >= M.MOD` it uses Lucas's theorem on the base-`P` digits, so the answer is exact modulo `P` for every `n`. A negative `n` gives 0. - **cost**: O(1) amortized for `n < M.MOD`; O(log_P n) otherwise - **traps**: never Examples: - `type Z = Mod<1_000_000_007>; Comb().choose(5, 2) == Z(10)` - `type Z = Mod<1_000_000_007>; Comb().choose(5, 6) == Z(0)` - `type Z = Mod<7>; Comb().choose(10, 3) == Z(1)` - `type Z = Mod<7>; Comb().choose(7, 1) == Z(0)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/mod.cp#L253) ### `Comb.arrange` ```cp fn arrange(self, n: Int, k: Int) -> M ``` The number of ordered selections of `k` out of `n` things, `n! / (n - k)!`; 0 when `k` is outside `0..=n`. The value is the falling factorial `n (n - 1) ... (n - k + 1)` reduced modulo `P`: 0 when those `k` numbers include a multiple of `P`, else `fact(n % P) / fact((n - k) % P)`, so it is exact for `n >= M.MOD` too. - **cost**: O(1) amortized - **traps**: never Examples: - `type Z = Mod<1_000_000_007>; Comb().arrange(5, 2) == Z(20)` - `type Z = Mod<7>; Comb().arrange(9, 2) == Z(2)` - `type Z = Mod<7>; Comb().arrange(8, 2) == Z(0)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/mod.cp#L271) ### `Comb.multichoose` ```cp fn multichoose(self, n: Int, k: Int) -> M ``` The number of ways to put `n` equal balls into `k` boxes (stars and bars): `choose(n + k - 1, n)`. `multichoose(0, 0)` is 1 (the empty placement) and `multichoose(n, 0)` is 0 for `n > 0`; a negative `n` or `k` gives 0. - **cost**: O(1) amortized - **traps**: never Examples: - `type Z = Mod<1_000_000_007>; Comb().multichoose(3, 2) == Z(4)` - `type Z = Mod<1_000_000_007>; Comb().multichoose(2, 3) == Z(6)` - `type Z = Mod<1_000_000_007>; Comb().multichoose(0, 0) == Z(1)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/mod.cp#L287) ### `Comb.catalan` ```cp fn catalan(self, n: Int) -> M ``` The `n`-th Catalan number, `choose(2n, n) - choose(2n, n + 1)`. The difference form needs no division by `n + 1`, so it stays exact when `n + 1` is a multiple of `P`. - **cost**: O(1) amortized - **traps**: when `n < 0` Examples: - `type Z = Mod<1_000_000_007>; Comb().catalan(0) == Z(1)` - `type Z = Mod<1_000_000_007>; Comb().catalan(4) == Z(14)` - `type Z = Mod<7>; Comb().catalan(4) == Z(0)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/mod.cp#L302) ### `Comb.derange` ```cp fn derange(self, n: Int) -> M ``` The number of derangements `!n`: permutations of `n` things with no fixed point. `!0 = 1`, `!1 = 0`, and `!n = (n - 1)(!(n - 1) + !(n - 2))`; the values are tabled like the factorials. - **cost**: O(1) amortized, O(n) table - **traps**: when `n < 0` Examples: - `type Z = Mod<1_000_000_007>; Comb().derange(0) == Z(1)` - `type Z = Mod<1_000_000_007>; Comb().derange(4) == Z(9)` - `type Z = Mod<1_000_000_007>; Comb().derange(5) == Z(44)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/mod.cp#L316) ### `Comb.multinomial` ```cp fn multinomial(self, ks: List) -> M ``` The multinomial coefficient `(sum ks)! / prod(k!)`; 0 if any `k < 0`. It is computed as the product of `choose(k_1 + ... + k_i, k_i)`, so Lucas applies and the result is exact modulo `P` even when `sum ks >= M.MOD`. - **cost**: O(ks.len) amortized - **empty**: 1 (the empty multinomial) - **traps**: never Examples: - `type Z = Mod<1_000_000_007>; Comb().multinomial([2, 1]) == Z(3)` - `type Z = Mod<1_000_000_007>; Comb().multinomial([1, 1, 1]) == Z(6)` - `type Z = Mod<1_000_000_007>; Comb().multinomial([2, -1]) == Z(0)` - `type Z = Mod<1_000_000_007>; Comb().multinomial([]) == Z(1)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/mod.cp#L335) ## `Barrett` ```cp pub struct Barrett(m: Int, im: U64) ``` O(1) reduction. Fast Barrett modular multiplier for a runtime modulus `1 <= m < 2^31`. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/mod.cp#L345) ### `Barrett.new` ```cp fn new(m: Int) -> Barrett ``` A Barrett multiplier for the runtime modulus `m`, `1 <= m < 2^31`: precomputes `im = floor((2^64 - 1) / m) + 1` (wrapping, so 0 for `m == 1`). - **cost**: O(1) - **traps**: when `m` is outside `1..2^31` Examples: - `Barrett(7).mul(3, 5) == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/mod.cp#L352) ### `Barrett.mul` ```cp fn mul(self, a: Int, b: Int) -> Int ``` `(a * b) % m` without a hardware division, for `a, b` in `0..m`. - **cost**: O(1) - **traps**: when `a` or `b` is outside `0..m` Examples: - `Barrett(7).mul(3, 5) == 1` - `Barrett(1_000_000_007).mul(1_000_000_006, 1_000_000_006) == 1` - `Barrett(1).mul(0, 0) == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/mod.cp#L363) ### `Barrett.reduce` ```cp fn reduce(self, a: U64) -> Int ``` `a % m`, for `a < m * m`. - **cost**: O(1) - **traps**: when `a >= m * m` Examples: - `Barrett(7).reduce(48) == 6` - `Barrett(7).reduce(0) == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/mod.cp#L373) ## `PrimePowerComb` ```cp pub struct PrimePowerComb(p: Int, e: Int, pe: Int) ``` O(p^e) build, O(log_p n) query. Binomial coefficients modulo a prime power `p^e` (Granville's theorem). [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/mod.cp#L378) ### `PrimePowerComb.new` ```cp fn new(p: Int, e: Int) -> PrimePowerComb ``` Tables for binomial coefficients modulo `p^e`: the factorials with every factor of `p` removed, modulo `p^e`. - **cost**: O(p^e) time and memory - **traps**: when `p` is not prime, or `e < 1`, or `p^e` overflows `Int` Examples: - `PrimePowerComb(2, 3).choose(6, 3) == 4` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/mod.cp#L387) ### `PrimePowerComb.free_fact` ```cp fn free_fact(self, n: Int) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/mod.cp#L398) ### `PrimePowerComb.p_count` ```cp fn p_count(self, n: Int) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/mod.cp#L407) ### `PrimePowerComb.choose` ```cp fn choose(self, n: Int, k: Int) -> Int ``` `C(n, k) mod p^e`, by Granville's generalization of Lucas's theorem; 0 when `k` is outside `0..=n`. - **cost**: O(log_p n) - **traps**: never Examples: - `PrimePowerComb(2, 3).choose(6, 3) == 4` - `PrimePowerComb(3, 2).choose(9, 3) == 3` - `PrimePowerComb(3, 2).choose(5, 7) == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/mod.cp#L423) ## `ModComb` ```cp pub struct ModComb(m: Int) ``` O(sum p_i^e_i) build, O(omega(m) log n) query. Binomial coefficients modulo any `m >= 1` via CRT. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/mod.cp#L432) ### `ModComb.new` ```cp fn new(m: Int) -> ModComb ``` Binomial coefficients modulo any `m >= 1`: factor `m` and build one `PrimePowerComb` per prime power, combined by CRT. - **cost**: O(sum p_i^e_i) - **traps**: when `m < 1` Examples: - `ModComb(12).choose(6, 3) == 8` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/mod.cp#L441) ### `ModComb.choose` ```cp fn choose(self, n: Int, k: Int) -> Int ``` `C(n, k) mod m`, by CRT over the prime powers of `m`; 0 when `k` is outside `0..=n`. With `m == 1` every answer is 0. - **cost**: O(omega(m) log n) - **traps**: never Examples: - `ModComb(12).choose(6, 3) == 8` - `ModComb(10).choose(5, 2) == 0` - `ModComb(1).choose(5, 2) == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/mod.cp#L454) --- # ntt URL: /docs/ref/std/ntt Generated from [spec/std/ntt.cp](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/ntt.cp) by `cpl doc --format json`. ## `Curved` ```cp pub enum Curved = Both | Right | Neither ``` Which arguments of a convolution over a semiring other than `(+, *)` have the shape that makes it fast: convex for `min`, concave for `max`. `Neither` asks for the O(n m) loop by name. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/ntt.cp#L239) ### `Curved.Both` ```cp Both ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/ntt.cp#L239) ### `Curved.Right` ```cp Right ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/ntt.cp#L239) ### `Curved.Neither` ```cp Neither ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/ntt.cp#L239) ## `Disjoint` ```cp pub struct Disjoint ``` The index op of a subset convolution: `i | j` over disjoint pairs `i & j == 0`. A value with a transform impl, so user libraries can define more index ops the same way. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/ntt.cp#L243) ## `subset` ```cp pub const subset = Disjoint() ``` `on: subset` in `convolve`. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/ntt.cp#L246) ## `SosOver` ```cp pub enum SosOver = Sub | Sup ``` Direction of a sum-over-subsets (SOS) zeta/Mobius transform. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/ntt.cp#L300) ### `SosOver.Sub` ```cp Sub ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/ntt.cp#L300) ### `SosOver.Sup` ```cp Sup ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/ntt.cp#L300) ## `RelaxedConvolve` ```cp pub struct RelaxedConvolve

``` O(log^2 n) amortized per step, O(n log^2 n) total. Online (relaxed) NTT convolution: supply `(a[k], b[k])` one step at a time and immediately receive `c[k] = sum_{i=0..=k} a[i] * b[k - i]`. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/ntt.cp#L382) ### `RelaxedConvolve.new` ```cp fn new() -> RelaxedConvolve

``` An empty online convolution: no values pushed yet. - **cost**: O(1) - **traps**: never Examples: - `type Z = Mod<17>; var rc = RelaxedConvolve<17>(); rc.push(Z(0), Z(0)) == Z(0)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/ntt.cp#L392) ### `RelaxedConvolve.push` ```cp fn push(mut self, ai: Mod

, bi: Mod

) -> Mod

``` Append `a[k] = ai` and `b[k] = bi` at the next index `k` and return `c[k] = sum_{i=0..=k} a[i] * b[k - i]`. `c[k]` depends only on values already pushed, so `a[k+1]` and `b[k+1]` may be computed from it: the shape of online DP like `f[k] = sum f[i] g[k - i]`. - **cost**: O(log^2 k) amortized - **traps**: when `k` reaches the largest NTT length `P` supports Examples: - `type Z = Mod<17>; var rc = RelaxedConvolve<17>(); rc.push(Z(1), Z(3)) == Z(3)` - `type Z = Mod<17>; var rc = RelaxedConvolve<17>(); rc.push(Z(1), Z(3)); rc.push(Z(2), Z(4)) == Z(10)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/ntt.cp#L404) ## `SemiRelaxedConvolve` ```cp pub struct SemiRelaxedConvolve

``` O(log^2 n) amortized per step. Semi-relaxed NTT convolution against a fixed `b` (supply `a[k]` online and immediately receive `c[k] = sum_{i=0..=k} a[i] * b[k - i]`). [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/ntt.cp#L422) ### `SemiRelaxedConvolve.new` ```cp fn new(b: List>) -> SemiRelaxedConvolve

``` An online convolution against the fixed polynomial `b`, nothing pushed yet. `b` is zero-padded as far as the pushes go, so pushing past `b.len` is allowed; an empty `b` makes every `c[k]` zero. - **cost**: O(b.len) - **empty**: every pushed `c[k]` is zero - **traps**: never Examples: - `type Z = Mod<17>; var sc = SemiRelaxedConvolve<17>([Z(1), Z(2)]); sc.push(Z(1)) == Z(1)` - `type Z = Mod<17>; let e: List = []; var sc = SemiRelaxedConvolve<17>(e); sc.push(Z(5)) == Z(0)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/ntt.cp#L437) ### `SemiRelaxedConvolve.push` ```cp fn push(mut self, ai: Mod

) -> Mod

``` Append `a[k] = ai` at the next index `k` and return `c[k] = sum_{i=0..=k} a[i] * b[k - i]`. - **cost**: O(log^2 k) amortized - **traps**: when `k` reaches the largest NTT length `P` supports Examples: - `type Z = Mod<17>; var sc = SemiRelaxedConvolve<17>([Z(1), Z(2)]); sc.push(Z(1)); sc.push(Z(2)); sc.push(Z(5)) == Z(9)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/ntt.cp#L444) --- # pair URL: /docs/ref/std/pair Generated from [spec/std/pair.cp](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/pair.cp) by `cpl doc --format json`. ## `Pair` ```cp pub struct Pair(lo: V, hi: V) ``` An unordered pair `{lo, hi}` of distinct positions of `V`, `lo` before `hi`. `Pair` is a domain of `V.count * (V.count - 1) / 2` positions, so `[Pair]T` stores one value per pair, packed, with no diagonal and no mirrored half. It walks by `hi`, then by `lo`: `(0, 1)`, `(0, 2)`, `(1, 2)`, `(0, 3)`, ..., which is the order a lower triangle is given in (row `i` lists the pairs with every earlier `j`), so `read<[Pair]Int>()` reads one. An array over it takes two positions in either order: `d[u, v] == d[v, u]`, trapping when `u == v`. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/pair.cp#L9) ### `Pair.new` ```cp fn new(u: V, v: V) -> Pair ``` The pair of `u` and `v`, in either order: the smaller position becomes `lo`. - **cost**: O(1) - **traps**: when `u == v` Examples: - `Pair<0..4>(3, 1).lo == 1` - `Pair<0..4>(3, 1) == Pair<0..4>(1, 3)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/pair.cp#L16) ### `Pair.at` ```cp fn at(u: V, v: V) -> ?Pair ``` The pair of `u` and `v` in either order, or `None` when `u == v`: the non-trapping [`new`](Pair.new). - **cost**: O(1) - **traps**: never Examples: - `Pair<0..4>.at(2, 2) == None` - `Pair<0..4>.at(2, 0) == Some(Pair<0..4>(0, 2))` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/pair.cp#L27) ### `Pair.other` ```cp fn other(self, v: V) -> V ``` The end of the pair that is not `v`: `p.other(p.lo) == p.hi` and `p.other(p.hi) == p.lo`. - **cost**: O(1) - **traps**: when `v` is neither `self.lo` nor `self.hi` Examples: - `Pair<0..4>(1, 3).other(3) == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/pair.cp#L34) --- # persistent URL: /docs/ref/std/persistent Generated from [spec/std/persistent.cp](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/persistent.cp) by `cpl doc --format json`. ## `Version` ```cp pub struct Version(root ``` Opaque version handle for `PersistentSegTree`. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/persistent.cp#L9) ## `PersistentSegTree` ```cp pub struct PersistentSegTree(m: Monoid) ``` Path-copying persistent segment tree over a domain `D` and monoid `Monoid`. `set` and `update` return a new `Version` in O(log n) time and memory; `fold` and `get` take O(log n). [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/persistent.cp#L13) ### `PersistentSegTree.new` ```cp fn new(op: M, a: ?[D]T = None, fill: ?T = None) -> PersistentSegTree ``` Build version 0 over `D` from `a:`, a uniform `fill:`, or the monoid identity everywhere, and keep it as `base`. Every later write returns a new `Version`; no version is ever changed. - **cost**: O(n) time and memory with `a:` or `fill:`, O(1) otherwise, for n = `|D|` - **empty**: an empty `D` gives a tree whose every fold is the identity - **traps**: when both `a:` and `fill:` are given Examples: - `var t = PersistentSegTree(+, a: [1, 2, 3]); t.all(t.base) == 6` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/persistent.cp#L26) ### `PersistentSegTree.push_node` ```cp fn push_node(mut self, l: Int, r: Int, v: T) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/persistent.cp#L40) ### `PersistentSegTree.build_list` ```cp fn build_list(mut self, vals: List, nl: Int, nr: Int) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/persistent.cp#L47) ### `PersistentSegTree.base` ```cp fn base(self) -> Version ``` The version built by `new`. - **cost**: O(1) - **traps**: never Examples: - `var t = PersistentSegTree(+, a: [1, 2, 3]); t.get(t.base, 0) == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/persistent.cp#L59) ### `PersistentSegTree.set_rec` ```cp fn set_rec(mut self, u: Int, nl: Int, nr: Int, idx: Int, x: T) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/persistent.cp#L62) ### `PersistentSegTree.set` ```cp fn set(mut self, v: Version, i: D, x: T) -> Version ``` A new version equal to `v` with position `i` set to `x`. `v` and every other version are unchanged; the new version shares all but the O(log n) copied nodes with `v`. - **cost**: O(log n) time and memory - **traps**: when `i` is not in `D`, or `v` did not come from this tree Examples: - `var t = PersistentSegTree(+, a: [1, 2, 3]); let v = t.set(t.base, 1, 10); t.all(v) == 14 and t.all(t.base) == 6` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/persistent.cp#L80) ### `PersistentSegTree.update_rec` ```cp fn update_rec(mut self, u: Int, nl: Int, nr: Int, idx: Int, f: T -> T) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/persistent.cp#L83) ### `PersistentSegTree.update` ```cp fn update(mut self, v: Version, i: D, f: T -> T) -> Version ``` A new version equal to `v` with position `i` replaced by `f` of its value in `v`. `f` is called once. - **cost**: O(log n) time and memory, one call of `f` - **traps**: when `i` is not in `D`, or `v` did not come from this tree Examples: - `var t = PersistentSegTree(+, a: [1, 2, 3]); let v = t.update(t.base, 2, x => x * 5); t.get(v, 2) == 15 and t.get(t.base, 2) == 3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/persistent.cp#L101) ### `PersistentSegTree.get` ```cp fn get(self, v: Version, i: D) -> T ``` The value at position `i` in version `v`. - **cost**: O(log n) - **traps**: when `i` is not in `D`, or `v` did not come from this tree Examples: - `var t = PersistentSegTree(+, a: [1, 2, 3]); t.get(t.base, 1) == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/persistent.cp#L109) ### `PersistentSegTree.fold_rec` ```cp fn fold_rec(self, u: Int, nl: Int, nr: Int, ql: Int, qr: Int) -> T ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/persistent.cp#L121) ### `PersistentSegTree.fold` ```cp fn fold(self, v: Version, r: Range) -> T ``` The fold of `r` in version `v`, left to right, so a non-commutative monoid sees its elements in position order. - **cost**: O(log n) - **empty**: the monoid identity - **traps**: when a non-empty `r` reaches outside `D`, or `v` did not come from this tree Examples: - `var t = PersistentSegTree(+, a: [1, 2, 3]); t.fold(t.base, 1..3) == 5` - `var t = PersistentSegTree(+, a: [1, 2, 3]); t.fold(t.base, 2..2) == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/persistent.cp#L135) ### `PersistentSegTree.all` ```cp fn all(self, v: Version) -> T ``` The fold of every position in version `v`, read from its root. - **cost**: O(1) - **empty**: the monoid identity when `D` is empty - **traps**: when `v` did not come from this tree Examples: - `var t = PersistentSegTree(+, a: [1, 2, 3]); let v = t.set(t.base, 0, 0); t.all(v) == 5` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/persistent.cp#L146) ### `PersistentSegTree.reserve` ```cp fn reserve(mut self, nodes: Int) ``` Preallocate room for `nodes` tree nodes in total, so later writes do not regrow the arena. Changes no version. - **cost**: O(nodes) - **traps**: when `nodes < 0` Examples: - `var t = PersistentSegTree(+, a: [1, 2, 3]); t.reserve(100); t.all(t.base) == 6` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/persistent.cp#L154) ### `PersistentSegTree.right_while` ```cp fn right_while(self, v: Version, from: Cut, ok: T -> Bool) -> Cut ``` The rightmost cut `b` at or after `from` such that `ok(fold(v, from..b))` holds, reading version `v`. Law: `ok` is monotone (once false, false for every longer range) and `ok(identity)` holds. - **cost**: O(log n) calls of `ok` - **ties**: the rightmost qualifying cut - **traps**: when `from` is not a cut of `D`, when `ok(identity)` is false, or `v` did not come from this tree Examples: - `var t = PersistentSegTree(+, a: [1, 2, 3]); t.right_while(t.base, 0, s => s <= 3) == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/persistent.cp#L169) ### `PersistentSegTree.rw` ```cp fn rw(self, u: Int, nl: Int, nr: Int, l: Int, ok: T -> Bool, acc: T) -> (Int, T, Bool) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/persistent.cp#L174) ### `PersistentSegTree.left_while` ```cp fn left_while(self, v: Version, to: Cut, ok: T -> Bool) -> Cut ``` The leftmost cut `b` at or before `to` such that `ok(fold(v, b..to))` holds, reading version `v`. Law: `ok` is monotone (once false, false for every longer range) and `ok(identity)` holds. - **cost**: O(log n) calls of `ok` - **ties**: the leftmost qualifying cut - **traps**: when `to` is not a cut of `D`, when `ok(identity)` is false, or `v` did not come from this tree Examples: - `var t = PersistentSegTree(+, a: [1, 2, 3]); t.left_while(t.base, 3, s => s <= 5) == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/persistent.cp#L194) ### `PersistentSegTree.lw` ```cp fn lw(self, u: Int, nl: Int, nr: Int, h: Int, ok: T -> Bool, acc: T) -> (Int, T, Bool) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/persistent.cp#L199) ### `PersistentSegTree.diff_kth` ```cp fn diff_kth(self, hi: Version, lo: Version, k: Int) -> ?D ``` For a tree of counts under `+`, the position of the `k`-th item (1-based) in the difference `hi - lo` (0-based, like `RangeKth.kth`), walking both versions at once; `None` when the difference holds at most `k` items. A position with count `c` holds `c` items. Law: `hi` was derived from `lo` by adding counts, so no position of `hi - lo` is negative. - **cost**: O(log n) - **ties**: items at one position are interchangeable; the position is returned - **traps**: when `k < 0`, or a version did not come from this tree Examples: - `var t = PersistentSegTree(+, a: [0, 0, 0, 0]); let v1 = t.set(t.base, 1, 1); let v2 = t.set(v1, 3, 2); t.diff_kth(v2, t.base, 1) == Some(3) and t.diff_kth(v2, t.base, 3) == None` - `var t = PersistentSegTree(+, a: [0, 0, 0, 0]); let v1 = t.set(t.base, 1, 1); let v2 = t.set(v1, 3, 2); t.diff_kth(v2, v1, 0) == Some(3)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/persistent.cp#L221) ## `RangeKth` ```cp pub struct RangeKth ``` Static range k-th smallest and range rank queries over `[D]T`. Built in O(n log n) using prefix versions of a persistent count tree; queries run in O(log n). [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/persistent.cp#L241) ### `RangeKth.new` ```cp fn new(a: [D]T) -> RangeKth ``` Build the static structure over `a`: one persistent count tree over the sorted distinct values per prefix of `a`. `a` is copied; later changes to it are not seen. - **cost**: O(n log n) time and memory for n = `a.len` - **empty**: an empty `a` builds; every query range is then empty - **order**: queries take ranges of `a`'s domain - **traps**: never Examples: - `RangeKth([5, 1, 4, 2]).kth(0..4, 0) == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/persistent.cp#L256) ### `RangeKth.lower_val` ```cp fn lower_val(self, x: T) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/persistent.cp#L270) ### `RangeKth.upper_val` ```cp fn upper_val(self, x: T) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/persistent.cp#L279) ### `RangeKth.inc` ```cp fn inc(mut self, root: Int, m: Int, pos: Int) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/persistent.cp#L288) ### `RangeKth.kth` ```cp fn kth(self, r: Range, k: Int) -> T ``` The `k`-th smallest element (0-based) of `a` over `r`, counting repeats. - **cost**: O(log n) - **empty**: traps (no `k` is in range) - **ties**: equal values are indistinguishable; the value is returned - **traps**: when `k < 0` or `k >= r.len`, or `r` reaches outside `D` Examples: - `RangeKth([5, 1, 4, 2]).kth(1..4, 1) == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/persistent.cp#L318) ### `RangeKth.count_prefix` ```cp fn count_prefix(self, u: Int, v: Int, nl: Int, nr: Int, limit: Int) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/persistent.cp#L337) ### `RangeKth.count_le` ```cp fn count_le(self, r: Range, x: T) -> Int ``` The number of elements of `a` over `r` that are at most `x`. - **cost**: O(log n) - **empty**: 0 - **traps**: when a non-empty `r` reaches outside `D` Examples: - `RangeKth([5, 1, 4, 2]).count_le(0..4, 4) == 3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/persistent.cp#L351) ### `RangeKth.count_lt` ```cp fn count_lt(self, r: Range, x: T) -> Int ``` The number of elements of `a` over `r` that are less than `x`. - **cost**: O(log n) - **empty**: 0 - **traps**: when a non-empty `r` reaches outside `D` Examples: - `RangeKth([5, 1, 4, 2]).count_lt(0..4, 4) == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/persistent.cp#L363) ### `RangeKth.count_in` ```cp fn count_in(self, r: Range, lo_v: T, hi_v: T) -> Int ``` The number of elements of `a` over `r` in `lo_v ..= hi_v` (both ends inclusive); 0 when `lo_v > hi_v`. - **cost**: O(log n) - **empty**: 0 - **traps**: when a non-empty `r` reaches outside `D` Examples: - `RangeKth([5, 1, 4, 2]).count_in(0..4, 2, 5) == 3` - `RangeKth([5, 1, 4, 2]).count_in(0..4, 5, 2) == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/persistent.cp#L376) ## `PersistentLazySegTree` ```cp pub struct PersistentLazySegTree(act: Action) ``` O(q log |D|) space. Path-copying persistent segment tree with lazy range updates: every `apply`/`set` returns a new `Version` in O(log |D|) time and memory. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/persistent.cp#L382) ### `PersistentLazySegTree.push_node` ```cp fn push_node(mut self, l: Int, r: Int, v: T, f: F) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/persistent.cp#L389) ### `PersistentLazySegTree.build_list` ```cp fn build_list(mut self, vals: List, nl: Int, nr: Int) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/persistent.cp#L397) ### `PersistentLazySegTree.tagged` ```cp fn tagged(mut self, u: Int, span: Int, f: F) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/persistent.cp#L404) ### `PersistentLazySegTree.apply_rec` ```cp fn apply_rec(mut self, u: Int, nl: Int, nr: Int, ql: Int, qr: Int, f: F) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/persistent.cp#L407) ### `PersistentLazySegTree.set_rec` ```cp fn set_rec(mut self, u: Int, nl: Int, nr: Int, idx: Int, x: T) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/persistent.cp#L415) ### `PersistentLazySegTree.fold_rec` ```cp fn fold_rec(self, u: Int, nl: Int, nr: Int, ql: Int, qr: Int, acc: F) -> T ``` `acc` holds the tags of the ancestors of `u`, which are newer than every tag below them. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/persistent.cp#L425) ### `PersistentLazySegTree.new` ```cp fn new(act: Action, a: ?[D]T = None, fill: ?T = None) -> PersistentLazySegTree ``` Build version 0 over `D` from `a:`, a uniform `fill:`, or the identity of `act`'s monoid, and keep it as `base`. Range writes copy O(log n) nodes and their pending tags, never changing an older version. - **cost**: O(n) time and memory with `a:` or `fill:`, O(1) otherwise, for n = `|D|` - **empty**: an empty `D` gives a tree whose every fold is the identity - **traps**: when both `a:` and `fill:` are given Examples: - `var t = PersistentLazySegTree(Action(apply: (d, x, span) => x + d * span), a: [1, 2, 3]); t.all(t.base) == 6` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/persistent.cp#L440) ### `PersistentLazySegTree.base` ```cp fn base(self) -> Version ``` The version built by `new`. - **cost**: O(1) - **traps**: never Examples: - `var t = PersistentLazySegTree(Action(apply: (d, x, span) => x + d * span), a: [1, 2, 3]); t.get(t.base, 2) == 3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/persistent.cp#L454) ### `PersistentLazySegTree.apply` ```cp fn apply(mut self, v: Version, r: Range, f: F) -> Version ``` A new version equal to `v` with the tag `f` applied to every position of `r`. - **cost**: O(log n) time and memory - **empty**: an empty `r` returns a version equal to `v` - **traps**: when a non-empty `r` reaches outside `D`, or `v` did not come from this tree Examples: - `var t = PersistentLazySegTree(Action(apply: (d, x, span) => x + d * span), a: [1, 2, 3]); let v = t.apply(t.base, 0..2, 10); t.all(v) == 26 and t.all(t.base) == 6` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/persistent.cp#L463) ### `PersistentLazySegTree.set` ```cp fn set(mut self, v: Version, i: D, x: T) -> Version ``` A new version equal to `v` with position `i` set to `x`, discarding tags pending above it. - **cost**: O(log n) time and memory - **traps**: when `i` is not in `D`, or `v` did not come from this tree Examples: - `var t = PersistentLazySegTree(Action(apply: (d, x, span) => x + d * span), a: [1, 2, 3]); let v = t.apply(t.base, 0..3, 1); let w = t.set(v, 0, 0); t.all(w) == 7` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/persistent.cp#L473) ### `PersistentLazySegTree.fold` ```cp fn fold(self, v: Version, r: Range) -> T ``` The fold of `r` in version `v`, left to right, with every applied tag accounted for. - **cost**: O(log n) - **empty**: the monoid identity - **traps**: when a non-empty `r` reaches outside `D`, or `v` did not come from this tree Examples: - `var t = PersistentLazySegTree(Action(apply: (d, x, span) => x + d * span), a: [1, 2, 3]); let v = t.apply(t.base, 1..3, 1); t.fold(v, 1..3) == 7` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/persistent.cp#L482) ### `PersistentLazySegTree.get` ```cp fn get(self, v: Version, i: D) -> T ``` The value at position `i` in version `v`, with every applied tag accounted for. - **cost**: O(log n) - **traps**: when `i` is not in `D`, or `v` did not come from this tree Examples: - `var t = PersistentLazySegTree(Action(apply: (d, x, span) => x + d * span), a: [1, 2, 3]); let v = t.apply(t.base, 1..3, 1); t.get(v, 1) == 3 and t.get(t.base, 1) == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/persistent.cp#L492) ### `PersistentLazySegTree.all` ```cp fn all(self, v: Version) -> T ``` The fold of every position in version `v`, read from its root. - **cost**: O(1) - **empty**: the monoid identity when `D` is empty - **traps**: when `v` did not come from this tree Examples: - `var t = PersistentLazySegTree(Action(apply: (d, x, span) => x + d * span), a: [1, 2, 3]); t.all(t.apply(t.base, 0..3, 2)) == 12` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/persistent.cp#L501) ## `PersistentArray` ```cp pub struct PersistentArray ``` O(q log |D|) space. Persistent array over domain `D`: O(log |D|) `get` and path-copying `set`. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/persistent.cp#L505) ### `PersistentArray.push_node` ```cp fn push_node(mut self, l: Int, r: Int, v: T) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/persistent.cp#L511) ### `PersistentArray.build_list` ```cp fn build_list(mut self, vals: List, nl: Int, nr: Int) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/persistent.cp#L518) ### `PersistentArray.set_rec` ```cp fn set_rec(mut self, u: Int, nl: Int, nr: Int, idx: Int, x: T) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/persistent.cp#L525) ### `PersistentArray.new` ```cp fn new(a: ?[D]T = None, fill: ?T = None) -> PersistentArray ``` Build version 0 over `D` from `a:` or a uniform `fill:`, and keep it as `base`. - **cost**: O(n) time and memory for n = `|D|` - **empty**: an empty `D` gives an array with no positions - **traps**: when both or neither of `a:` and `fill:` are given Examples: - `var p = PersistentArray(fill: 7); p.get(p.base, 0) == 7` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/persistent.cp#L537) ### `PersistentArray.base` ```cp fn base(self) -> Version ``` The version built by `new`. - **cost**: O(1) - **traps**: never Examples: - `var p = PersistentArray(a: [1, 2, 3]); p.get(p.base, 2) == 3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/persistent.cp#L555) ### `PersistentArray.get` ```cp fn get(self, v: Version, i: D) -> T ``` The value at position `i` in version `v`. - **cost**: O(log n) - **traps**: when `i` is not in `D`, or `v` did not come from this array Examples: - `var p = PersistentArray(a: [1, 2, 3]); p.get(p.base, 1) == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/persistent.cp#L563) ### `PersistentArray.set` ```cp fn set(mut self, v: Version, i: D, x: T) -> Version ``` A new version equal to `v` with position `i` set to `x`; `v` is unchanged. - **cost**: O(log n) time and memory - **traps**: when `i` is not in `D`, or `v` did not come from this array Examples: - `var p = PersistentArray(a: [1, 2, 3]); let v = p.set(p.base, 0, 9); p.get(v, 0) == 9 and p.get(p.base, 0) == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/persistent.cp#L580) ## `PMultiset` ```cp pub struct PMultiset ``` O(log |D|) per update. Hashed persistent multiset over domain `D`: O(1) equality, O(log |D|) lexicographic comparison (`desc: true` compares largest element first). [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/persistent.cp#L585) ### `PMultiset.empty` ```cp fn empty() -> PMultiset ``` The empty multiset over `D`. Every multiset is an immutable value; `==` compares two in O(1) by hash. - **cost**: O(1) - **traps**: never Examples: - `PMultiset<0..10>.empty().count(3) == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/persistent.cp#L594) ### `PMultiset.with` ```cp fn with(self, x: D) -> PMultiset ``` A new multiset with one more copy of `x`; `self` is unchanged. - **cost**: O(log |D|) time and memory - **traps**: when `x` is not in `D` Examples: - `let s = PMultiset<0..10>.empty().with(3).with(3); s.count(3) == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/persistent.cp#L601) ### `PMultiset.without` ```cp fn without(self, x: D) -> PMultiset ``` A new multiset with one copy of `x` removed, or equal to `self` when `x` is absent; `self` is unchanged. - **cost**: O(log |D|) time and memory - **traps**: when `x` is not in `D` Examples: - `let s = PMultiset<0..10>.empty().with(3).with(3); s.without(3).count(3) == 1 and s.count(3) == 2` - `let s = PMultiset<0..10>.empty(); s.without(3) == s` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/persistent.cp#L610) ### `PMultiset.count` ```cp fn count(self, x: D) -> Int ``` The number of copies of `x`. - **cost**: O(log |D|) - **traps**: when `x` is not in `D` Examples: - `PMultiset<0..10>.empty().with(4).count(4) == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/persistent.cp#L617) ### `PMultiset.cmp` ```cp fn cmp(self, other: PMultiset, desc: Bool = false) -> Int ``` Compare the elements of `self` and `other` as sorted sequences, lexicographically: ascending, or largest first with `desc: true`. A proper prefix is smaller. Returns `-1`, `0` or `1`. The first differing key is found by hash in O(log |D|); `0` exactly when the multisets are equal. - **cost**: O(log |D|) - **ties**: `0` only for equal multisets - **traps**: never Examples: - `let e = PMultiset<0..10>.empty(); e.with(1).with(3).cmp(e.with(2)) == -1` - `let e = PMultiset<0..10>.empty(); e.with(1).with(3).cmp(e.with(2), desc: true) == 1` - `let e = PMultiset<0..10>.empty(); e.with(1).cmp(e.with(1).with(2)) == -1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/persistent.cp#L631) --- # poly URL: /docs/ref/std/poly Generated from [spec/std/poly.cp](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/poly.cp) by `cpl doc --format json`. ## `Poly` ```cp pub struct Poly(c: List) ``` O(n) storage. Algebraic polynomial / formal power series wrapper over `T` (lowest degree first). [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/poly.cp#L650) ### `Poly.new` ```cp fn new(c: List) -> Poly ``` A polynomial with coefficients `c`, lowest degree first, stored as given (trailing zeros kept, so `len` is `c.len`). - **cost**: O(n) - **empty**: `Poly.new([])` is the zero polynomial - **traps**: never Examples: - `Poly([1, 2, 0]).len == 3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/poly.cp#L658) ### `Poly.from_int` ```cp fn from_int(v: Int) -> Poly ``` The constant polynomial `v`, with one coefficient `T.from_int(v)`. - **cost**: O(1) - **traps**: never Examples: - `Poly.from_int(5).at(0) == 5` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/poly.cp#L665) ### `Poly.zero` ```cp fn zero() -> Poly ``` The zero polynomial `0`, with no coefficients. - **cost**: O(1) - **traps**: never Examples: - `Poly.zero.deg() == -1 and Poly.zero.len == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/poly.cp#L672) ### `Poly.one` ```cp fn one() -> Poly ``` The constant polynomial `1`. - **cost**: O(1) - **traps**: never Examples: - `Poly.one.at(0) == 1 and Poly.one.deg() == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/poly.cp#L679) ### `Poly.x` ```cp fn x() -> Poly ``` The indeterminate `x`: coefficients `[0, 1]`. - **cost**: O(1) - **traps**: never Examples: - `Poly.x.deg() == 1 and Poly.x.at(1) == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/poly.cp#L686) ### `Poly.len` ```cp fn len(self) -> Int ``` The number of stored coefficients, trailing zeros included. - **cost**: O(1) - **traps**: never Examples: - `Poly([1, 0]).len == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/poly.cp#L693) ### `Poly.deg` ```cp fn deg(self) -> Int ``` The degree: the highest index with a nonzero coefficient, `-1` for the zero polynomial. Stored trailing zeros do not count. - **cost**: O(1) plus the number of stored trailing zeros - **traps**: never Examples: - `Poly([1, 2, 0]).deg() == 1` - `Poly([0, 0]).deg() == -1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/poly.cp#L702) ### `Poly.is_zero` ```cp fn is_zero(self) -> Bool ``` Whether all coefficients are zero (including when there are None). - **cost**: O(1) plus the number of stored trailing zeros - **traps**: never Examples: - `Poly([0, 0]).is_zero() and not Poly.one.is_zero()` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/poly.cp#L712) ### `Poly.at` ```cp fn at(self, i: Int) -> T ``` Read coefficient `i` (0 when `i >= self.len`). - **cost**: O(1) - **traps**: when `i < 0` Examples: - `Poly([1, 2]).at(1) == 2 and Poly([1, 2]).at(5) == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/poly.cp#L719) ### `Poly.set` ```cp fn set(mut self, i: Int, v: T) ``` Write coefficient `i`, growing with zeros if needed. - **cost**: O(1), or O(i) when it grows - **traps**: when `i < 0` Examples: - `var p = Poly([1]); p.set(3, 7); p.len == 4 and p.at(2) == 0 and p.at(3) == 7` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/poly.cp#L726) ### `Poly.deriv` ```cp fn deriv(self) -> Poly ``` The formal derivative `f'(x)`, as the free `deriv` does on the coefficients. - **cost**: O(n) - **traps**: never Examples: - `Poly([1, 2, 3]).deriv().at(1) == 6` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/poly.cp#L736) ### `Poly.integral` ```cp fn integral(self) -> Poly ``` The formal integral with zero constant term, as the free `integral`. - **cost**: O(n) - **traps**: when `T` cannot divide by some `k` in `1..=n` (`n >= P` for `Mod

`) Examples: - `type Z = Mod<998244353>; Poly([1, 2, 3]).integral().at(3) == Z(1)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/poly.cp#L746) ### `Poly.transposed_mul` ```cp fn transposed_mul(self, b: Poly) -> Poly ``` The transposed (middle) product: `out[i] = sum_j self[i + j] * b[j]` over `j in 0..b.len`, for each `i` in `0..max(0, self.len - b.len + 1)` (only complete sums). - **cost**: O((n + m) log(n + m)) - **traps**: never Examples: - `Poly([1, 2, 3, 4]).transposed_mul(Poly([1, 1])).len == 3` - `Poly([1, 2, 3, 4]).transposed_mul(Poly([1, 1])).at(2) == 7` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/poly.cp#L759) ### `Poly.truncated` ```cp fn truncated(self, n: Int) -> Poly ``` Truncate or zero-pad to exactly `n` coefficients (mod `x^n`). - **cost**: O(n) - **traps**: when `n < 0` Examples: - `Poly([1, 2, 3]).truncated(2).len == 2` - `Poly([1]).truncated(3).at(2) == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/poly.cp#L767) ### `Poly.inv` ```cp fn inv(self, n: Int) -> Poly ``` The multiplicative inverse mod `x^n` (`self[0] != 0`), as the free `inv`. - **cost**: O(n log n) - **traps**: as the free `inv`: `n < 0`, or `n > 0` with `self.at(0) == 0` Examples: - `type Z = Mod<998244353>; Poly([1, -1]).inv(3).at(2) == Z(1)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/poly.cp#L776) ### `Poly.log` ```cp fn log(self, n: Int) -> Poly ``` The formal logarithm mod `x^n` (`self[0] == 1`), as the free `log`. - **cost**: O(n log n) - **traps**: as the free `log`: `n < 0`, or `n > 0` with `self.at(0) != 1` Examples: - `type Z = Mod<998244353>; Poly([1, 2, 1]).log(3).at(2) == Z(-1)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/poly.cp#L784) ### `Poly.exp` ```cp fn exp(self, n: Int) -> Poly ``` The formal exponential mod `x^n` (`self[0] == 0`), as the free `exp`. - **cost**: O(n log n) - **traps**: as the free `exp`: `n < 0`, or `n > 0` with `self.at(0) != 0` Examples: - `type Z = Mod<998244353>; Poly([0, 2]).exp(3).at(2) == Z(2)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/poly.cp#L792) ### `Poly.pow` ```cp fn pow(self, k: Int, n: Int) -> Poly ``` The formal power `self(x)^k mod x^n`, as the free `pow`. - **cost**: O(n log n) - **traps**: as the free `pow`: `n < 0`, or `k < 0` with `self.at(0) == 0` Examples: - `type Z = Mod<998244353>; Poly([1, 1]).pow(3, 4).at(2) == Z(3)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/poly.cp#L800) ### `Poly.sqrt` ```cp fn sqrt(self, n: Int) -> ?Poly ``` The formal square root mod `x^n`, or `None`, as the free `sqrt`. - **cost**: O(n log n + log^2 P) - **traps**: when `n < 0` Examples: - `type Z = Mod<998244353>; Poly([1, 2, 1]).sqrt(3)!.at(1) == Z(1)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/poly.cp#L808) ### `Poly.eval` ```cp fn eval(self, x: T) -> T ``` The value at `x` by Horner's rule. - **cost**: O(n) - **traps**: never Examples: - `Poly([1, 2, 3]).eval(2) == 17` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/poly.cp#L815) ### `Poly.shift` ```cp fn shift(self, c: T) -> Poly ``` The Taylor shift `self(x + c)`, as `taylor_shift`. - **cost**: O(n log n) - **traps**: when `T` cannot divide by the factorials below `n` (`n > P` for `Mod

`) Examples: - `type Z = Mod<998244353>; Poly([0, 0, 1]).shift(Z(1)).at(1) == Z(2)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/poly.cp#L826) ## `Poly` ```cp impl Add for Poly ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/poly.cp#L828) ### `Poly.add` ```cp fn add(a, b) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/poly.cp#L829) ## `Poly` ```cp impl Sub for Poly ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/poly.cp#L831) ### `Poly.sub` ```cp fn sub(a, b) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/poly.cp#L832) ## `Poly` ```cp impl Neg for Poly ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/poly.cp#L834) ### `Poly.neg` ```cp fn neg(a) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/poly.cp#L835) ## `Poly` ```cp impl Mul for Poly ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/poly.cp#L837) ### `Poly.mul` ```cp fn mul(a, b) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/poly.cp#L839) ## `Poly` ```cp impl Div for Poly ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/poly.cp#L841) ### `Poly.div` ```cp fn div(a, b) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/poly.cp#L843) ## `SubproductTree` ```cp pub struct SubproductTree

``` O(m log^2 m) build. Prebuilt product tree over points `xs` for multipoint evaluation, transposed evaluation, and interpolation. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/poly.cp#L847) ### `SubproductTree.new` ```cp fn new(xs: List>, keep: Int = -1) -> SubproductTree

``` Build the subproduct tree for the points `xs`: leaf `i` is `x - xs[i]` and each node the product of its children. With `keep >= 0` every stored product is truncated mod `x^keep`, which is all `eval_transposed` needs; `eval` and `interpolate` need the full tree (`keep < 0`, the default). - **cost**: O(m log^2 m) time, O(m log m) space - **empty**: a tree over no points - **traps**: when a transform length exceeds what `P` supports Examples: - `type Z = Mod<998244353>; let xs: List = [0, 1, 2]; let t = SubproductTree(xs); t.eval([Z(1), Z(2), Z(3)]) == [Z(1), Z(6), Z(17)]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/poly.cp#L859) ### `SubproductTree.eval` ```cp fn eval(self, f: List>) -> List> ``` Evaluate `f` at every point in the tree: `[f(x) for x in xs]`. - **cost**: O((deg f + m) log^2 m) - **empty**: `[]` for a tree over no points - **order**: one value per point, in `xs` order - **traps**: when the tree was built with `keep >= 0` Examples: - `type Z = Mod<998244353>; let xs: List = [1, 2]; SubproductTree(xs).eval([Z(0), Z(0), Z(1)]) == [Z(1), Z(4)]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/poly.cp#L868) ### `SubproductTree.eval_transposed` ```cp fn eval_transposed(self, c: List>) -> List> ``` Transposed multipoint evaluation (Bostan-Lecerf-Schost / Tellegen's principle): the transpose of `eval` on polynomials of degree `< m`, so `out[k] = sum_i c[i] * xs[i]^k` for `k in 0..m`. - **cost**: O(m log^2 m) - **empty**: `[]` for a tree over no points - **order**: by power `k`, increasing - **traps**: when `c.len != m`, or `keep` is in `0..m` Examples: - `type Z = Mod<998244353>; let xs: List = [1, 2]; SubproductTree(xs).eval_transposed([Z(1), Z(1)]) == [Z(2), Z(3)]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/poly.cp#L878) ### `SubproductTree.interpolate` ```cp fn interpolate(self, ys: List>) -> List> ``` The unique polynomial of degree `< m` taking values `ys` at the tree's points, as exactly `m` coefficients. The points must be distinct. - **cost**: O(m log^2 m) - **empty**: `[]` - **order**: lowest degree first - **traps**: when `ys.len != m`, two points are equal, or the tree was built with `keep >= 0` Examples: - `type Z = Mod<998244353>; let xs: List = [0, 1, 2]; SubproductTree(xs).interpolate([Z(1), Z(4), Z(9)]) == [Z(1), Z(2), Z(1)]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/poly.cp#L888) --- # prefix URL: /docs/ref/std/prefix Generated from [spec/std/prefix.cp](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/prefix.cp) by `cpl doc --format json`. ## `FillOrder` ```cp pub enum FillOrder = Forward | Reverse ``` Fill direction for an append-only `Prefix.filling(...)` table. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/prefix.cp#L39) ### `FillOrder.Forward` ```cp Forward ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/prefix.cp#L39) ### `FillOrder.Reverse` ```cp Reverse ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/prefix.cp#L39) ## `FillPrefix` ```cp pub struct FillPrefix ``` Append-only 1-D prefix/suffix sum table returned by `Prefix.filling(...)`. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/prefix.cp#L42) ### `FillPrefix.set` ```cp fn set(mut self, i: D, x: T) ``` Write the next cell in fill order (`D.first..=D.last` for `Forward`, reverse for `Reverse`). Each position is written exactly once, in fill order; the table tracks the next position it expects. every position is written) - **cost**: O(1) - **traps**: when `i` is not the next position in fill order (out of order, repeated, or after Examples: - `domain D = 0..3; var f = Prefix.filling(); f.set(0, 5); f.set(1, 7); f.prefix(2) == 12` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/prefix.cp#L56) ### `FillPrefix.prefix` ```cp fn prefix(self, b: Cut) -> T ``` The sum of everything left of boundary `b`; zero at the first cut. of `b` is written last) - **cost**: O(1) - **traps**: when a position left of `b` is not yet written (with `Reverse`, every position left Examples: - `domain D = 0..3; var f = Prefix.filling(); f.set(0, 5); f.set(1, 7); f.prefix(1) == 5` - `domain D = 0..3; var f = Prefix.filling(); f.prefix(0) == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/prefix.cp#L73) ### `FillPrefix.fold` ```cp fn fold(self, r: Range) -> T ``` The sum of `a[i]` for `i` in `r`, or `0` when `r` is empty. - **cost**: O(1) - **empty**: zero, whatever has been written - **traps**: when `r` is non-empty and contains a position not yet written Examples: - `domain D = 0..3; var f = Prefix.filling(); f.set(0, 5); f.set(1, 7); f.fold(0..2) == 12` - `domain D = 0..3; var f = Prefix.filling(order: FillOrder.Reverse); f.set(2, 4); f.set(1, 6); f.fold(1..) == 10` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/prefix.cp#L86) ## `Prefix` ```cp pub struct Prefix ``` Prefix sums over a domain `D`, a 2-D grid `(R, C)`, or a `List`, of `Int`s, `F64`s, `Mod`s, or anything else with `+`, `-` and a zero. Construct statically with `prefix(a)` in O(|D|) / O(|R| * |C|) / O(a.len), or incrementally with `Prefix<...>.filling(order: FillOrder.Forward | FillOrder.Reverse)` and O(1) `.set(...)` in fill order; `.fold(...)` and `.prefix(...)` are O(1) over the already-filled prefix or suffix. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/prefix.cp#L98) ### `Prefix.new` ```cp fn new(a: [D]T) -> Prefix ``` Build 1-D prefix sums over `a: [D]T`; `prefix(a)` calls it. - **cost**: O(|D|) time and space - **empty**: a table whose every query is zero - **traps**: never Examples: - `domain D = 0..3; let p = Prefix([D] v => 1 + Int(v)); p.all == 6` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/prefix.cp#L107) ### `Prefix.filling` ```cp fn filling(order: FillOrder = FillOrder.Forward) -> FillPrefix ``` Create an append-only 1-D prefix/suffix sum table filled via `.set(i, x)` in `order`. `Forward` writes `D.first` to `D.last` and answers queries over the written prefix; `Reverse` writes `D.last` to `D.first` and answers queries over the written suffix. - **cost**: O(|D|) time and space - **traps**: never Examples: - `domain D = 0..3; var f = Prefix.filling(); f.set(0, 2); f.fold(0..1) == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/prefix.cp#L121) ### `Prefix.prefix` ```cp fn prefix(self, b: Cut) -> T ``` The sum of everything left of boundary `b`: zero at the first cut, `all` at the last. - **cost**: O(1) - **traps**: never Examples: - `domain D = 0..3; let p = Prefix([D] v => 1 + Int(v)); p.prefix(2) == 3` - `domain D = 0..3; let p = Prefix([D] v => 1 + Int(v)); p.prefix(0) == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/prefix.cp#L132) ### `Prefix.of_cuts` ```cp fn of_cuts(p: [D.cuts]T) -> Prefix ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/prefix.cp#L134) ### `Prefix.fold` ```cp fn fold(self, r: Range) -> T ``` The sum of `a[i]` for `i` in `r`, or `0` when `r` is empty: `prefix(r.r) - prefix(r.l)`. - **cost**: O(1) - **empty**: zero - **traps**: never Examples: - `domain D = 0..3; let p = Prefix([D] v => 1 + Int(v)); p.fold(1..=2) == 5` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/prefix.cp#L142) ### `Prefix.cyclic_sum` ```cp fn cyclic_sum(self, r: RingRange) -> T ``` The sum over a wrapping run of positions, e.g. `a.ring.span(i, k)`: the part from `r.start` to `D.last` plus the part from `D.first` to `r.end` when it wraps. - **cost**: O(1) - **empty**: zero for an empty span - **traps**: never Examples: - `domain D = 0..3; let a: [D]Int = [D] v => 1 + Int(v); Prefix(a).cyclic_sum(a.ring.span(2, 2)) == 4` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/prefix.cp#L153) ### `Prefix.get` ```cp fn get(self, i: D) -> T ``` Recover the original element `a[i]`, as `prefix(i.r) - prefix(i.l)`. - **cost**: O(1) - **traps**: never Examples: - `domain D = 0..3; let p = Prefix([D] v => 1 + Int(v)); p.get(1) == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/prefix.cp#L164) ### `Prefix.suffix` ```cp fn suffix(self, b: Cut) -> T ``` The sum of everything right of boundary `b`: `all - prefix(b)`, zero at the last cut. - **cost**: O(1) - **traps**: never Examples: - `domain D = 0..3; let p = Prefix([D] v => 1 + Int(v)); p.suffix(1) == 5` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/prefix.cp#L172) ### `Prefix.all` ```cp fn all(self) -> T ``` The sum of the entire domain: `prefix` at the last cut, zero for an empty domain. - **cost**: O(1) - **empty**: zero - **traps**: never Examples: - `domain D = 0..3; let p = Prefix([D] v => 1 + Int(v)); p.all == 6` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/prefix.cp#L181) ### `Prefix.first_ge` ```cp fn first_ge(self, target: T) -> ?Cut ``` The first boundary `b` with `prefix(b) >= target`, or `None` when even `all` is smaller. A binary search over the cuts, which needs `prefix` non-decreasing, so every element must be non-negative; the table records at build time whether that holds. A `target` at or below zero gives the first cut. - **cost**: O(log |D|) - **empty**: the first cut when `target <= 0`, else `None` - **ties**: the first in cut order (zero elements make equal prefixes) - **traps**: when some element is negative Examples: - `Int([2, 0, 3].scan(+).first_ge(2)!) == 1` - `[2, 0, 3].scan(+).first_ge(6) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/prefix.cp#L196) ### `Prefix.first_gt` ```cp fn first_gt(self, target: T) -> ?Cut ``` The first boundary `b` with `prefix(b) > target`, or `None` when `all <= target`. The same search as `first_ge`, with the same non-negative requirement. - **cost**: O(log |D|) - **empty**: the first cut when `target < 0`, else `None` - **ties**: the first in cut order - **traps**: when some element is negative Examples: - `Int([2, 0, 3].scan(+).first_gt(2)!) == 3` - `[2, 0, 3].scan(+).first_gt(5) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/prefix.cp#L216) ## `Diff` ```cp pub struct Diff ``` Offline difference array: `Diff()` for 1-D ranges or `Diff()` for 2-D grids. O(1) range/rectangle `add`, O(|D|) or O(|R| * |C|) `finish`. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/prefix.cp#L463) ### `Diff.new` ```cp fn new() -> Diff ``` Create an all-zero 1-D difference array over `D`. - **cost**: O(|D|) time and space - **traps**: never Examples: - `domain D = 0..3; Diff().finish()[D(1)] == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/prefix.cp#L471) ### `Diff.add` ```cp fn add(mut self, r: Range, x: T) ``` Add `x` to every position in `r`; an empty `r` changes nothing. - **cost**: O(1) - **empty**: no effect - **traps**: never Examples: - `domain D = 0..4; var d = Diff(); d.add(1..3, 5); d.add(2..=3, 1); [d.finish()[v] for v in D] == [0, 5, 6, 1]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/prefix.cp#L481) ### `Diff.finish` ```cp fn finish(self) -> [D]T ``` The accumulated values across `D`: each position's total of the `add`s covering it. The structure is unchanged and can take more `add`s. - **cost**: O(|D|) time and space - **empty**: an empty array - **order**: keyed by `D` - **traps**: never Examples: - `domain D = 0..3; var d = Diff(); d.add(0..=1, 2); d.finish()[D(1)] == 2 and d.finish()[D(2)] == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/prefix.cp#L494) ## `SweepAdd` ```cp pub struct SweepAdd ``` O(|D|) space. Online sweep-line difference accumulator: schedule future range adds in O(1) and advance a cursor through `D` in `order` in O(1) per position. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/prefix.cp#L548) ### `SweepAdd.new` ```cp fn new(order: FillOrder = FillOrder.Forward) -> SweepAdd ``` Create an all-zero online sweep accumulator in `order` (`Forward` or `Reverse`), with no position advanced yet. - **cost**: O(|D|) time and space - **traps**: never Examples: - `domain D = 0..3; var s = SweepAdd(); s.advance(0) == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/prefix.cp#L559) ### `SweepAdd.add` ```cp fn add(mut self, r: Range, x: T) ``` Schedule `+x` across `r`, which must start at or ahead of the current sweep cursor: no position of `r` may have been advanced past already. An empty `r` changes nothing. - **cost**: O(1) - **empty**: no effect - **traps**: when `r` is non-empty and holds a position already advanced to Examples: - `domain D = 0..4; var s = SweepAdd(); s.add(1..=2, 5); let a = s.advance(0); let b = s.advance(1); a == 0 and b == 5` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/prefix.cp#L570) ### `SweepAdd.advance` ```cp fn advance(mut self, i: D) -> T ``` Advance the cursor to `i`, the next position in fill order, and return the accumulated value there: the total of every scheduled `add` covering `i`. - **cost**: O(1) - **traps**: when `i` is not the next position in fill order Examples: - `domain D = 0..3; var s = SweepAdd(order: FillOrder.Reverse); s.add(1..=2, 4); let a = s.advance(2); s.add(0..=1, 1); let b = s.advance(1); a == 4 and b == 5` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/prefix.cp#L585) ### `SweepAdd.current` ```cp fn current(self) -> T ``` The accumulated value at the most recently advanced position, as `advance` returned it. - **cost**: O(1) - **traps**: when no position has been advanced yet Examples: - `domain D = 0..3; var s = SweepAdd(); s.add(0..=0, 7); s.advance(0); s.current == 7` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/prefix.cp#L594) ## `ArithDiff` ```cp pub struct ArithDiff ``` O(|D|) space. Second-order offline difference array for arithmetic-progression range adds: O(1) `add_arith`, O(|D|) `finish`. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/prefix.cp#L599) ### `ArithDiff.new` ```cp fn new() -> ArithDiff ``` Create an all-zero second-order difference array over `D`. - **cost**: O(|D|) time and space - **traps**: never Examples: - `domain D = 0..3; ArithDiff().finish()[D(2)] == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/prefix.cp#L608) ### `ArithDiff.add_arith` ```cp fn add_arith(mut self, r: Range, start: T, step: T) ``` Add `start + step * (i.ord - r.start.ord)` to every position `i` in `r`: `start` at the first position of `r`, growing by `step` per position. An empty `r` changes nothing. - **cost**: O(1) - **empty**: no effect - **traps**: never Examples: - `domain D = 0..5; var d = ArithDiff(); d.add_arith(1..=3, 10, 2); [d.finish()[v] for v in D] == [0, 10, 12, 14, 0]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/prefix.cp#L620) ### `ArithDiff.add` ```cp fn add(mut self, r: Range, x: T) ``` Add a constant `x` to every position in `r`: `add_arith(r, x, 0)`. - **cost**: O(1) - **empty**: no effect - **traps**: never Examples: - `domain D = 0..5; var d = ArithDiff(); d.add_arith(1..=3, 10, 2); d.add(0..2, 1); [d.finish()[v] for v in D] == [1, 11, 12, 14, 0]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/prefix.cp#L633) ### `ArithDiff.finish` ```cp fn finish(self) -> [D]T ``` The accumulated values across `D`. The structure is unchanged and can take more adds. - **cost**: O(|D|) time and space - **empty**: an empty array - **order**: keyed by `D` - **traps**: never Examples: - `domain D = 0..3; var d = ArithDiff(); d.add_arith(0..=2, 1, 1); [d.finish()[v] for v in D] == [1, 2, 3]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/prefix.cp#L645) --- # rand URL: /docs/ref/std/rand Generated from [spec/std/rand.cp](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/rand.cp) by `cpl doc --format json`. ## `Rng` ```cp pub struct Rng(s: U64) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/rand.cp#L4) ### `Rng.new` ```cp fn new(seed: Int) -> Rng ``` A deterministic stream of random bits seeded by `seed`. The state is `U64(seed)` (two's complement for negative seeds) and each `next()` is one splitmix64 step, so equal seeds give equal streams on every build and target. There is no time-seeded constructor: tests and stress runs replay exactly. - **cost**: O(1) - **traps**: never Examples: - `var r = Rng(0); r.next() == 0xE220A8397B1DCDAF` - `var a = Rng(7); var b = Rng(7); a.next() == b.next()` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/rand.cp#L15) ### `Rng.next` ```cp fn next(mut self) -> U64 ``` The next 64 random bits: one splitmix64 step. The state advances by `0x9E3779B97F4A7C15` (wrapping) and the result is the splitmix64 mix of the new state: `z ^= z >> 30; z *= 0xBF58476D1CE4E5B9; z ^= z >> 27; z *= 0x94D049BB133111EB; z ^= z >> 31`, all wrapping. Every other `Rng` method draws its bits from `next`. - **cost**: O(1) - **traps**: never Examples: - `var r = Rng(0); r.next(); r.next() == 0x6E789E6AA1B965F4` - `var r = Rng(1); r.next() == 10451216379200822465` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/rand.cp#L26) ### `Rng.int` ```cp fn int(mut self, lo: Int, hi: Int) -> Int ``` A uniformly random integer in `lo..=hi`, both ends inclusive, from one `next()`. With `n = hi - lo + 1`, the result is `lo + ((U128(next()) * n) >> 64)`: Lemire's multiply-high map, which uses exactly one draw (bias at most `n / 2^64`). - **cost**: O(1) - **empty**: traps - **traps**: when `lo > hi` Examples: - `var r = Rng(1); let x = r.int(1, 6); 1 <= x and x <= 6` - `var r = Rng(5); r.int(4, 4) == 4` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/rand.cp#L41) ### `Rng.float` ```cp fn float(mut self) -> F64 ``` A uniformly random `F64` in `[0, 1)`: the top 53 bits of `next()` times `2^-53`. - **cost**: O(1) - **traps**: never Examples: - `var r = Rng(5); let x = r.float(); 0.0 <= x and x < 1.0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/rand.cp#L52) ### `Rng.chance` ```cp fn chance(mut self, p: F64) -> Bool ``` True with probability `p`: `float() < p`. `p <= 0` is always false and `p >= 1` always true; both still consume one draw so the stream stays aligned whatever `p` is. - **cost**: O(1) - **traps**: never Examples: - `var r = Rng(3); r.chance(1.0) == true` - `var r = Rng(3); r.chance(0.0) == false` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/rand.cp#L62) ### `Rng.pick` ```cp fn pick(mut self, xs: S) -> ?T ``` A uniformly random element of `xs`: `xs` at position `int(0..xs.len)`. The position is zero-based, so any key type works. An empty `xs` returns `None` without drawing. - **cost**: O(1) - **empty**: `None`, and no draw - **traps**: never Examples: - `var r = Rng(1); r.pick([7]) == Some(7)` - `var r = Rng(1); let x = r.pick([4, 5, 6]).unwrap(); 4 <= x and x <= 6` - `let e: List = []; var r = Rng(1); r.pick(e) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/rand.cp#L74) ### `Rng.shuffle` ```cp fn shuffle(mut self, mut a: S) ``` Shuffle `a` in place, uniformly (Fisher-Yates). For `i` from `a.len - 1` down to `1`, swap positions `i` and `int(0..=i)`. Positions are zero-based, so this works on any `IndexedMut`: a `List`, a `[D]T` over any domain, a `Str`. Keys stay where they are; only the values move. - **cost**: O(n) - **empty**: no change, and no draw - **traps**: never Examples: - `var r = Rng(2); var a = [3, 1, 2]; r.shuffle(mut a); a.sorted() == [1, 2, 3]` - `var r = Rng(2); var a = [9]; r.shuffle(mut a); a == [9]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/rand.cp#L88) ### `Rng.perm` ```cp fn perm(mut self) -> [D]D ``` A uniformly random permutation of the domain `D`, as a `[D]D`. It is the identity `[D]D` shuffled with `shuffle`, so a seed fixes the result. Every element of `D` appears exactly once among the values. - **cost**: O(n) - **order**: keyed by `D`; the value at each key is uniformly random, each element of `D` once - **traps**: never Examples: - `domain V = 0..4; var r = Rng(4); let p = r.perm(); p.distinct().len == 4` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/rand.cp#L99) ### `Rng.sample` ```cp fn sample(mut self, k: Int, from: S) -> List ``` `k` elements of `from` at distinct positions, chosen uniformly, in random order. It runs a partial Fisher-Yates over a copy of the positions: for `i` in `0..k`, swap positions `i` and `int(i..n)`, then return the values at the first `k` positions. Equal values at different positions can both be chosen. - **cost**: O(|from|) - **empty**: `[]` when `k == 0` - **order**: the order drawn (random); a new `List`, keyed from 0 - **traps**: when `k` is not in `0..=from.len` Examples: - `var r = Rng(9); r.sample(3, from: [5, 6, 7]).sorted() == [5, 6, 7]` - `var r = Rng(9); r.sample(0, from: [5, 6, 7]) == []` - `var r = Rng(9); r.sample(2, from: [1, 1, 1]) == [1, 1]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/rand.cp#L116) --- # segtree URL: /docs/ref/std/segtree Generated from [spec/std/segtree.cp](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp) by `cpl doc --format json`. ## `SegTree` ```cp pub struct SegTree(m: Monoid) ``` Point update and range fold. The operation is a bare operator (`+`, `*`, `^`, `&`, `|`, `min`, `max`, `gcd`) or your own `Monoid(id, op)`: `SegTree(max, a)`, `SegTree(+)`, `SegTree(Monoid(Run.empty, Run.join), a)`. `set` and `fold` are O(log n), and so are `right_while` and `left_while`; memory is 2 * bit_ceil(n) values. The fold keeps the order of the positions, so non-commutative operations work. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L16) ### `SegTree.source` ```cp source: ?(D -> T) ``` What each position holds, for a tree built with `of`. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L25) ### `SegTree.new` ```cp fn new(op: ?M = None, a: ?[D]T = None, fill: ?T = None, act: A = NoAction(), over: ?Range = None) -> SegTree ``` A tree over `D` folding with `op`: built from `a`, filled with `fill`, or holding the identity everywhere when neither is given. `op` is a bare operator (`+`, `*`, `^`, `&`, `|`, `min`, `max`, `gcd`) or a `Monoid(id, op)`. `act:` adds range tags (`apply`, `apply_all`); with `act:` and no `op` the tree applies tags and reads points only. When the tag monoid is `Commutative` the tree skips push-down, which changes speed, never answers. `over: lo..hi` covers a huge `Int` range instead, making nodes on first touch; positions outside the touched ones hold `fill` or the identity. - **cost**: O(|D|); O(1) with `over:` - **empty**: an empty `D` gives a tree whose every fold is the identity - **order**: positions keep the domain `D` of `a` - **traps**: when both `a` and `fill` are given, or `over:` is given together with `a` Examples: - `SegTree(+, [1, 2, 3]).all == 6` - `SegTree<0..4, Int>(max, fill: 5).fold(1..3) == 5` - `SegTree<0..4, Int>(+).all == 0` - `var s = SegTree(+, over: 0..1_000_000_000); s.set(999_999_999, 4); s.all == 4` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L44) ### `SegTree.build` ```cp fn build(m: Monoid, a: ?[D]T, fill: ?T) -> SegTree ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L53) ### `SegTree.build_lazy` ```cp fn build_lazy(m: Monoid, a: ?[D]T, fill: ?T, resolved: Action) -> SegTree ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L64) ### `SegTree.put` ```cp fn put(self, p: Int, f: F) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L89) ### `SegTree.push` ```cp fn push(self, p: Int) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L98) ### `SegTree.open` ```cp fn open(self, l: Int, h: Int) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L107) ### `SegTree.pull_node` ```cp fn pull_node(self, p: Int) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L112) ### `SegTree.apply` ```cp fn apply(mut self, r: Range, f: F) ``` Apply tag `f` to every position of `r`: each fold over `r` then sees the values with `f` applied, through the action given to `act:`. - **cost**: O(log |D|) - **empty**: changes nothing - **traps**: when a non-empty `r` reaches outside `D` Examples: - `var s = SegTree(+, [1, 2, 3], act: add); s.apply(0..2, 10); s.all == 26` - `var s = SegTree(max, [1, 2, 3], act: add); s.apply(0..1, 5); s.all == 6` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L124) ### `SegTree.apply_all` ```cp fn apply_all(mut self, f: F) ``` Apply tag `f` to every position; `apply(D.all, f)`. - **cost**: O(1) amortized when the tags commute, else O(|D|) - **empty**: changes nothing for an empty `D` - **traps**: never Examples: - `var s = SegTree(+, [1, 2, 3], act: add); s.apply_all(1); s.all == 9` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L151) ### `SegTree.fold` ```cp fn fold(self, r: Range) -> T ``` The fold of the values in `r`, left to right: `op(op(a[l], a[l + 1]), ...)`. - **cost**: O(log |D|) - **empty**: the identity - **traps**: when a non-empty `r` reaches outside `D` Examples: - `var s = SegTree(+, [1, 2, 3], act: add); s.apply(1..3, 1); s.fold(1..3) == 7` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L161) ### `SegTree.right_while` ```cp fn right_while(self, from: Cut, ok: T -> Bool) -> Cut ``` The last cut `d` at or right of `from` such that `ok(fold(from..d))` holds. `ok` must be monotone (once false it stays false as `d` moves right) and true on the identity, so `from` itself always qualifies. Replaces `max_right`. - **cost**: O(log |D|) - **ties**: the rightmost qualifying cut - **traps**: when `ok(identity)` is false Examples: - `SegTree(+, [1, 2, 3, 4]).right_while((0..0).r, s => s <= 3) == (0..2).r` - `SegTree(+, [1, 2, 3, 4]).right_while((0..1).r, s => s <= 5) == (0..3).r` - `SegTree(+, [1, 2, 3, 4]).right_while((0..0).r, s => s <= 100) == (0..4).r` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L189) ### `SegTree.left_while` ```cp fn left_while(self, to: Cut, ok: T -> Bool) -> Cut ``` The first cut `d` at or left of `to` such that `ok(fold(d..to))` holds. `ok` must be monotone (once false it stays false as `d` moves left) and true on the identity, so `to` itself always qualifies. Replaces `min_left`. - **cost**: O(log |D|) - **ties**: the leftmost qualifying cut - **traps**: when `ok(identity)` is false Examples: - `SegTree(+, [1, 2, 3, 4]).left_while((0..4).r, s => s <= 7) == (0..2).r` - `SegTree(+, [1, 2, 3, 4]).left_while((0..4).r, s => s <= 3) == (0..4).r` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L220) ### `SegTree.of` ```cp fn of(op: M, f: D -> T) -> SegTree ``` A tree whose position `i` holds `f(i)`. `f` is kept: when something it reads changes, `refresh(i)` recomputes position `i`, so the formula is written once instead of at every update site. - **cost**: O(|D|), calling `f` once per position in key order - **empty**: an empty `D` gives a tree whose every fold is the identity - **order**: position `i` holds `f(i)` - **traps**: never Examples: - `let w = [1, 2, 3]; SegTree<0..3, Int>.of(+, i => w[i] * 2).all == 12` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L250) ### `SegTree.refresh` ```cp fn refresh(mut self, i: D) ``` Recompute position `i` as `f(i)` with the formula given to `of`, and update its ancestors. - **cost**: O(log |D|) plus one call of `f` - **traps**: when `i` is outside `D`, or the tree was not built with `of` Examples: - `var w = [1, 2, 3]; var s = SegTree<0..3, Int>.of(+, i => w[i]); w[1] = 10; s.refresh(1); s.all == 14` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L260) ### `SegTree.get` ```cp fn get(self, i: D) -> T ``` The value at position `i`, with every tag applied. - **cost**: O(1); O(log |D|) on a tree with `act:` - **traps**: when `i` is outside `D` Examples: - `SegTree(+, [4, 5, 6]).get(1) == 5` - `var s = SegTree(act: assign, [1, 2, 3]); s.apply(0..2, Some(9)); s.get(1) == 9` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L271) ### `SegTree.set` ```cp fn set(mut self, i: D, x: T) ``` Make position `i` hold `x`, replacing any tags applied to it, and update its ancestors. - **cost**: O(log |D|) - **traps**: when `i` is outside `D` Examples: - `var s = SegTree(+, [1, 2, 3]); s.set(0, 10); s.all == 15` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L282) ### `SegTree.at` ```cp fn at(mut self, i: D) -> lends mut T ``` Position `i` as a writable place: `st.at(i) += x`, `st.at(i) max= x`. The ancestors are updated when the write ends, so each use is one `set`; read with `get` instead. - **cost**: O(log |D|) per write - **traps**: when `i` is outside `D` Examples: - `var s = SegTree(+, [1, 2, 3]); s.at(0) += 5; s.all == 11` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L295) ### `SegTree.pull` ```cp fn pull(mut self, i: D) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L302) ### `SegTree.update` ```cp fn update(mut self, i: D, f: T -> T) ``` Replace the value `v` at `i` with `f(v)`; `set(i, f(get(i)))` in one walk. - **cost**: O(log |D|) plus one call of `f` - **traps**: when `i` is outside `D` Examples: - `var s = SegTree(+, [1, 2, 3]); s.update(2, x => x * 10); s.all == 33` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L314) ### `SegTree.all` ```cp fn all(self) -> T ``` The fold of every position, left to right. - **cost**: O(1) - **empty**: the identity for an empty `D` - **traps**: never Examples: - `SegTree(max, [3, 9, 4]).all == 9` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L323) ### `SegTree.monoid` ```cp fn monoid(self) -> Monoid ``` The operation the tree folds with, as its `(id, op)` pair. - **cost**: O(1) - **traps**: never Examples: - `SegTree(+, [1]).monoid.id == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L330) ### `SegTree.try_fold` ```cp fn try_fold(self, r: Range) -> ?T ``` The fold of `r`, or `None` when `r` is empty; for operations whose identity is only a sentinel. - **cost**: O(log |D|) - **empty**: `None` - **traps**: when a non-empty `r` reaches outside `D` Examples: - `SegTree(+, [1, 2]).try_fold(0..2) == Some(3)` - `SegTree(+, [1, 2]).try_fold(1..1) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L342) ### `SegTree.clear` ```cp fn clear(mut self, fill: ?T = None) ``` Make every position hold `fill`, or the identity when `fill` is `None`, dropping all pending tags; the storage is reused. A tree built with `of` keeps its formula. - **cost**: O(|D|) - **empty**: nothing to reset for an empty `D` - **traps**: never Examples: - `var s = SegTree(+, [1, 2, 3]); s.clear(); s.all == 0` - `var s = SegTree(+, [1, 2, 3]); s.clear(fill: 2); s.all == 6` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L355) ### `SegTree.walk` ```cp fn walk(self, r: Range) -> yields T ``` The values of the canonical nodes that exactly cover `r`: the maximal aligned blocks of the tree's `bit_ceil(|D|)` leaves inside `r`. Their fold, left to right, is `fold(r)`. - **cost**: O(log |D|) - **empty**: yields nothing - **order**: left to right; at most `2 * log2(bit_ceil(|D|))` values - **traps**: when a non-empty `r` reaches outside `D` Examples: - `SegTree(+, [1, 2, 3, 4]).walk(0..3).collect() == [3, 3]` - `SegTree(+, [1, 2, 3, 4]).walk(1..4).collect() == [2, 7]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L369) ## `MergeSortTree` ```cp pub struct MergeSortTree ``` Static merge-sort tree for orthogonal 2D range counting over `[D]T`. Build in O(n log n) time and memory; answer value-range counts over any `Range` in O(log^2 n). [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L485) ### `MergeSortTree.new` ```cp fn new(a: [D]T) -> MergeSortTree ``` A static tree over `a` whose nodes hold their values sorted, for counting values in a range. - **cost**: O(|D| log |D|) time and memory - **empty**: an empty `a` gives a tree where every count is 0 - **order**: positions keep the domain `D` of `a` - **traps**: never Examples: - `MergeSortTree([3, 1, 4, 1, 5]).count_lt(0..5, 3) == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L498) ### `MergeSortTree.lower_idx` ```cp fn lower_idx(self, u: Int, x: T) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L530) ### `MergeSortTree.upper_idx` ```cp fn upper_idx(self, u: Int, x: T) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L540) ### `MergeSortTree.count_lt` ```cp fn count_lt(self, r: Range, x: T) -> Int ``` The number of positions in `r` whose value is `< x`. - **cost**: O(log^2 |D|) - **empty**: 0 - **traps**: when a non-empty `r` reaches outside `D` Examples: - `MergeSortTree([3, 1, 4, 1, 5]).count_lt(0..5, 3) == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L556) ### `MergeSortTree.count_le` ```cp fn count_le(self, r: Range, x: T) -> Int ``` The number of positions in `r` whose value is `<= x`. - **cost**: O(log^2 |D|) - **empty**: 0 - **traps**: when a non-empty `r` reaches outside `D` Examples: - `MergeSortTree([3, 1, 4, 1, 5]).count_le(0..5, 3) == 3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L577) ### `MergeSortTree.count_in` ```cp fn count_in(self, r: Range, lo_v: T, hi_v: T) -> Int ``` The number of positions in `r` whose value lies in `lo_v..=hi_v`; 0 when `lo_v > hi_v`. - **cost**: O(log^2 |D|) - **empty**: 0 - **traps**: when a non-empty `r` reaches outside `D` Examples: - `MergeSortTree([3, 1, 4, 1, 5]).count_in(1..4, 1, 4) == 3` - `MergeSortTree([3, 1, 4, 1, 5]).count_in(0..5, 4, 3) == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L599) ### `MergeSortTree.count_gt` ```cp fn count_gt(self, r: Range, x: T) -> Int ``` The number of positions in `r` whose value is `> x`. - **cost**: O(log^2 |D|) - **empty**: 0 - **traps**: when a non-empty `r` reaches outside `D` Examples: - `MergeSortTree([3, 1, 4, 1, 5]).count_gt(0..5, 3) == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L609) ### `MergeSortTree.count_ge` ```cp fn count_ge(self, r: Range, x: T) -> Int ``` The number of positions in `r` whose value is `>= x`. - **cost**: O(log^2 |D|) - **empty**: 0 - **traps**: when a non-empty `r` reaches outside `D` Examples: - `MergeSortTree([3, 1, 4, 1, 5]).count_ge(0..5, 4) == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L619) ### `MergeSortTree.first_ge` ```cp fn first_ge(self, r: Range, x: T) -> ?T ``` The smallest value in `r` that is `>= x`, or `None`. - **cost**: O(log^2 |D|) - **empty**: `None` - **ties**: equal values are interchangeable; the value is returned, not a position - **traps**: when a non-empty `r` reaches outside `D` Examples: - `MergeSortTree([3, 1, 4, 1, 5]).first_ge(0..3, 2) == Some(3)` - `MergeSortTree([3, 1, 4, 1, 5]).first_ge(0..3, 5) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L631) ### `MergeSortTree.last_le` ```cp fn last_le(self, r: Range, x: T) -> ?T ``` The largest value in `r` that is `<= x`, or `None`. - **cost**: O(log^2 |D|) - **empty**: `None` - **ties**: equal values are interchangeable; the value is returned, not a position - **traps**: when a non-empty `r` reaches outside `D` Examples: - `MergeSortTree([3, 1, 4, 1, 5]).last_le(2..5, 3) == Some(1)` - `MergeSortTree([3, 1, 4, 1, 5]).last_le(2..5, 0) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L657) ## `SegTree2D` ```cp pub struct SegTree2D(m: Monoid) ``` O(|R| * |C|) space. Iterative 2D segment tree: point update and rectangle fold in O(log |R| * log |C|). [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L676) ### `SegTree2D.fold_row` ```cp fn fold_row(self, i: Int, cl: Int, ch: Int) -> T ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L679) ### `SegTree2D.new` ```cp fn new(op: M, a: ?[R, C]T = None, fill: ?T = None) -> SegTree2D ``` A grid tree over `(R, C)` folding with `op`: built from `a`, filled with `fill`, or holding the identity everywhere. `op` must be `Commutative`, since a rectangle is folded in row-blocks and column-blocks rather than in one order. - **cost**: O(|R| * |C|) - **empty**: an empty `R` or `C` gives a tree whose every fold is the identity - **order**: cells keep the domains `R` and `C` of `a` - **traps**: when both `a` and `fill` are given Examples: - `SegTree2D<0..3, 0..3, Int>(+, fill: 1).all == 9` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L703) ### `SegTree2D.get` ```cp fn get(self, r: R, c: C) -> T ``` The value of cell `(r, c)`. - **cost**: O(1) - **traps**: when `r` is outside `R` or `c` is outside `C` Examples: - `var g = SegTree2D<0..3, 0..3, Int>(+, fill: 1); g.set(1, 2, 7); g.get(1, 2) == 7` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L725) ### `SegTree2D.set` ```cp fn set(mut self, r: R, c: C, x: T) ``` Make cell `(r, c)` hold `x`. - **cost**: O(log |R| * log |C|) - **traps**: when `r` is outside `R` or `c` is outside `C` Examples: - `var g = SegTree2D<0..3, 0..3, Int>(+, fill: 1); g.set(0, 0, 5); g.all == 13` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L733) ### `SegTree2D.update` ```cp fn update(mut self, r: R, c: C, f: T -> T) ``` Replace the value `v` of cell `(r, c)` with `f(v)`. - **cost**: O(log |R| * log |C|) plus one call of `f` - **traps**: when `r` is outside `R` or `c` is outside `C` Examples: - `var g = SegTree2D<0..3, 0..3, Int>(+, fill: 1); g.update(2, 2, x => x + 1); g.all == 10` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L755) ### `SegTree2D.fold` ```cp fn fold(self, rows: Range, cols: Range) -> T ``` The fold of every cell in rows `rows` and columns `cols`. - **cost**: O(log |R| * log |C|) - **empty**: the identity when `rows` or `cols` is empty - **traps**: when a non-empty range reaches outside its domain Examples: - `SegTree2D<0..3, 0..3, Int>(+, fill: 1).fold(0..2, 1..3) == 4` - `SegTree2D<0..3, 0..3, Int>(+, fill: 1).fold(0..2, 1..1) == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L765) ### `SegTree2D.all` ```cp fn all(self) -> T ``` The fold of every cell. - **cost**: O(1) - **empty**: the identity for an empty grid - **traps**: never Examples: - `var g = SegTree2D<0..2, 0..2, Int>(max, fill: 0); g.set(1, 0, 8); g.all == 8` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L787) ## `WaveletMatrix` ```cp pub struct WaveletMatrix ``` O(|D| log V) build and memory. Wavelet matrix over non-negative integer values: O(log V) range k-th smallest, frequency, value-range count, predecessor/successor, and quantile sum. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L792) ### `WaveletMatrix.ones` ```cp fn ones(self, l: Int, i: Int) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L799) ### `WaveletMatrix.below` ```cp fn below(self, lo0: Int, hi0: Int, x: Int) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L801) ### `WaveletMatrix.new` ```cp fn new(a: [D]Int) -> WaveletMatrix ``` A wavelet matrix over the non-negative values of `a`, with one bit level per bit of the largest value (`V` below is that value plus one). - **cost**: O(|D| log V) time and memory - **empty**: an empty `a` gives a matrix where every count is 0 - **order**: positions keep the domain `D` of `a` - **traps**: when some value is negative Examples: - `WaveletMatrix([3, 1, 4, 1, 5]).kth(0..5, 2) == Some(3)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L822) ### `WaveletMatrix.kth` ```cp fn kth(self, r: Range, k: Int) -> ?Int ``` The `k`-th smallest value in `r`, counting from 0 and with repeats, or `None` when `k >= r.len`. - **cost**: O(log V) - **empty**: `None` - **ties**: equal values are counted once each - **traps**: when `k < 0`, or a non-empty `r` reaches outside `D` Examples: - `WaveletMatrix([3, 1, 4, 1, 5]).kth(0..5, 0) == Some(1)` - `WaveletMatrix([3, 1, 4, 1, 5]).kth(0..5, 2) == Some(3)` - `WaveletMatrix([3, 1, 4, 1, 5]).kth(0..5, 5) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L861) ### `WaveletMatrix.rank` ```cp fn rank(self, r: Range, x: Int) -> Int ``` The number of positions in `r` holding exactly `x`; 0 for any `x` outside `0..V`. - **cost**: O(log V) - **empty**: 0 - **traps**: when a non-empty `r` reaches outside `D` Examples: - `WaveletMatrix([3, 1, 4, 1, 5]).rank(0..5, 1) == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L883) ### `WaveletMatrix.count_lt` ```cp fn count_lt(self, r: Range, x: Int) -> Int ``` The number of positions in `r` whose value is `< x`. - **cost**: O(log V) - **empty**: 0 - **traps**: when a non-empty `r` reaches outside `D` Examples: - `WaveletMatrix([3, 1, 4, 1, 5]).count_lt(0..5, 4) == 3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L894) ### `WaveletMatrix.count_in` ```cp fn count_in(self, r: Range, lo_v: Int, hi_v: Int) -> Int ``` The number of positions in `r` whose value lies in `lo_v..=hi_v`; 0 when `lo_v > hi_v`. - **cost**: O(log V) - **empty**: 0 - **traps**: when a non-empty `r` reaches outside `D` Examples: - `WaveletMatrix([3, 1, 4, 1, 5]).count_in(0..5, 1, 3) == 3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L904) ### `WaveletMatrix.prev_val` ```cp fn prev_val(self, r: Range, x: Int) -> ?Int ``` The largest value in `r` that is `< x`, or `None`. - **cost**: O(log V) - **empty**: `None` - **ties**: equal values are interchangeable; the value is returned, not a position - **traps**: when a non-empty `r` reaches outside `D` Examples: - `WaveletMatrix([3, 1, 4, 1, 5]).prev_val(0..5, 3) == Some(1)` - `WaveletMatrix([3, 1, 4, 1, 5]).prev_val(0..5, 1) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L917) ### `WaveletMatrix.next_val` ```cp fn next_val(self, r: Range, x: Int) -> ?Int ``` The smallest value in `r` that is `> x`, or `None`. - **cost**: O(log V) - **empty**: `None` - **ties**: equal values are interchangeable; the value is returned, not a position - **traps**: when a non-empty `r` reaches outside `D` Examples: - `WaveletMatrix([3, 1, 4, 1, 5]).next_val(0..5, 3) == Some(4)` - `WaveletMatrix([3, 1, 4, 1, 5]).next_val(0..5, 5) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L930) ### `WaveletMatrix.quantile_sum` ```cp fn quantile_sum(self, r: Range, k: Int) -> Int ``` The sum of the `k` smallest values in `r`, with repeats. - **cost**: O(log V) - **empty**: 0 (only `k == 0` is allowed) - **ties**: equal values are counted once each - **traps**: when `k` is outside `0..=r.len`, or a non-empty `r` reaches outside `D` Examples: - `WaveletMatrix([3, 1, 4, 1, 5]).quantile_sum(0..5, 3) == 5` - `WaveletMatrix([3, 1, 4, 1, 5]).quantile_sum(1..3, 0) == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L943) ## `DynamicOrderTree` ```cp pub struct DynamicOrderTree ``` O(|D| log^2 |D|) space. Dynamic point-update + 2D range value-count and k-th structure (Fenwick of order trees) over `[D]T`. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L963) ### `DynamicOrderTree.bump` ```cp fn bump(mut self, i: Int, x: T, put: Bool) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L968) ### `DynamicOrderTree.below` ```cp fn below(self, end: Int, x: T, le: Bool) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L975) ### `DynamicOrderTree.span_count` ```cp fn span_count(self, r: Range, x: T, le: Bool) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L984) ### `DynamicOrderTree.new` ```cp fn new(a: [D]T) -> DynamicOrderTree ``` A structure over `a` answering value counts and order statistics on ranges while positions are reassigned. - **cost**: O(|D| log^2 |D|) time and memory - **empty**: an empty `a` gives a tree where every count is 0 - **order**: positions keep the domain `D` of `a` - **traps**: never Examples: - `DynamicOrderTree([3, 1, 4]).count_lt(0..3, 4) == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L997) ### `DynamicOrderTree.set` ```cp fn set(mut self, i: D, x: T) ``` Make position `i` hold `x`. - **cost**: O(log^2 |D|) - **traps**: when `i` is outside `D` Examples: - `var t = DynamicOrderTree([3, 1, 4]); t.set(0, 0); t.kth(0..3, 0) == Some(0)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L1007) ### `DynamicOrderTree.get` ```cp fn get(self, i: D) -> T ``` The value at position `i`. - **cost**: O(1) - **traps**: when `i` is outside `D` Examples: - `var t = DynamicOrderTree([3, 1, 4]); t.set(2, 9); t.get(2) == 9` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L1018) ### `DynamicOrderTree.count_lt` ```cp fn count_lt(self, r: Range, x: T) -> Int ``` The number of positions in `r` whose value is `< x`. - **cost**: O(log^2 |D|) - **empty**: 0 - **traps**: when a non-empty `r` reaches outside `D` Examples: - `DynamicOrderTree([3, 1, 4]).count_lt(1..3, 4) == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L1026) ### `DynamicOrderTree.count_in` ```cp fn count_in(self, r: Range, lo_v: T, hi_v: T) -> Int ``` The number of positions in `r` whose value lies in `lo_v..=hi_v`; 0 when `lo_v > hi_v`. - **cost**: O(log^2 |D|) - **empty**: 0 - **traps**: when a non-empty `r` reaches outside `D` Examples: - `DynamicOrderTree([3, 1, 4]).count_in(0..3, 1, 3) == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L1034) ### `DynamicOrderTree.kth` ```cp fn kth(self, r: Range, k: Int) -> ?T ``` The `k`-th smallest value in `r`, counting from 0 and with repeats, or `None` when `k >= r.len`. - **cost**: O(log^2 |D|) - **empty**: `None` - **ties**: equal values are counted once each - **traps**: when `k < 0`, or a non-empty `r` reaches outside `D` Examples: - `DynamicOrderTree([3, 1, 4]).kth(0..3, 1) == Some(3)` - `DynamicOrderTree([3, 1, 4]).kth(0..3, 3) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L1047) ## `MergeSeg` ```cp pub struct MergeSeg ``` O(q log |D|) space. Mergeable min-ordered set over domain `D` for lazily pruned minimum-alive queries (`MergeSeg.singleton`, `merge`, `first_alive`). [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L1051) ### `MergeSeg.push_raw` ```cp fn push_raw(mut self, x: D) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L1055) ### `MergeSeg.pop_min` ```cp fn pop_min(mut self) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L1069) ### `MergeSeg.singleton` ```cp fn singleton(x: D) -> MergeSeg ``` A set of positions of `D` holding only `x`, stored as a sparse binary tree over `D`. - **cost**: O(log |D|) - **traps**: when `x` is outside `D` Examples: - `MergeSeg<0..10>.singleton(3).first_alive(x => true) == Some(3)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L1095) ### `MergeSeg.merge` ```cp fn merge(self, other: MergeSeg) -> MergeSeg ``` The union of `self` and `other`. The result reuses the nodes of both, so neither input may be used afterwards. - **cost**: O(log |D|) amortized per node absorbed - **traps**: never Examples: - `var m = MergeSeg<0..10>.singleton(7).merge(MergeSeg<0..10>.singleton(3)); m.first_alive(x => true) == Some(3)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L1103) ### `MergeSeg.first_alive` ```cp fn first_alive(mut self, alive: D -> Bool) -> ?D ``` The smallest position `x` in the set with `alive(x)`, or `None`. Every position found dead on the way is removed for good, so `alive` must be monotone over time: a position never comes back to life. - **cost**: O(log |D|) amortized - **ties**: the smallest position in key order - **traps**: never Examples: - `var m = MergeSeg<0..10>.singleton(3).merge(MergeSeg<0..10>.singleton(7)); m.first_alive(x => x > 5) == Some(7)` - `var m = MergeSeg<0..10>.singleton(3).merge(MergeSeg<0..10>.singleton(7)); m.first_alive(x => x > 5); m.first_alive(x => true) == Some(7)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/segtree.cp#L1123) --- # seq URL: /docs/ref/std/seq Generated from [spec/std/seq.cp](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp) by `cpl doc --format json`. ## `Perm` ```cp pub type Perm = [V]V ``` Every value of `V` once, in some order. `cpl stress` makes and shrinks it as a permutation. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L15) ## `Compressed` ```cp pub struct Compressed(vals: [D]T) ``` The distinct values of a coordinate compression, in increasing order, indexed by their own domain `D`. `xs[i]` is the value at index `i`, `xs.at(val)` the index of a value that was compressed, and `xs.first_ge(val)` / `xs.last_le(val)` the nearest index (`?D`) for any value. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L755) ### `Compressed.get` ```cp fn get(self, i: D) -> T ``` O(1). The value at index `i`; `slice` takes a `Range`. - **cost**: O(1) - **traps**: never Examples: - `let (domain C, xs) = compress([30, 10]); xs.get(C.first!) == 10` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L761) ### `Compressed.slice` ```cp fn slice(self, r: Range) -> List ``` The compressed values over a range `r` of `xs.D`, as a list. - **cost**: O(r.len) - **empty**: `[]` for an empty `r` - **order**: increasing values; a new `List`, keyed from 0 - **traps**: never Examples: - `let (domain C, xs) = compress([3, 1, 2]); xs.slice(C.all) == [1, 2, 3]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L770) ### `Compressed.len` ```cp fn len(self) -> Int ``` How many distinct values there are. - **cost**: O(1) - **traps**: never Examples: - `compress([5, 5, 7]).1.len == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L777) ### `Compressed.at` ```cp fn at(self, val: T) -> D ``` The index of `val`, which must be one of the compressed values. - **cost**: O(log n) - **ties**: none: values are distinct - **traps**: when `val` was not compressed Examples: - `let (domain C, xs) = compress([30, 10]); xs.at(30) == C.last!` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L785) ### `Compressed.try_at` ```cp fn try_at(self, val: T) -> ?D ``` The index of `val` if it was compressed, or `None`. - **cost**: O(log n) - **traps**: never Examples: - `compress([30, 10]).1.try_at(20) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L795) ### `Compressed.contains` ```cp fn contains(self, val: T) -> Bool ``` Whether `val` is one of the compressed values. - **cost**: O(log n) - **traps**: never Examples: - `compress([30, 10]).1.contains(10) == true` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L803) ### `Compressed.first_ge` ```cp fn first_ge(self, val: T) -> ?D ``` The first index whose value is `>= val`, or `None`. - **cost**: O(log n) - **ties**: none: values are distinct - **traps**: never Examples: - `let (domain C, xs) = compress([10, 30]); xs.first_ge(20) == Some(C.last!)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L811) ### `Compressed.first_gt` ```cp fn first_gt(self, val: T) -> ?D ``` The first index whose value is `> val`, or `None`. - **cost**: O(log n) - **ties**: none: values are distinct - **traps**: never Examples: - `let (domain C, xs) = compress([10, 30]); xs.first_gt(30) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L819) ### `Compressed.last_le` ```cp fn last_le(self, val: T) -> ?D ``` The last index whose value is `<= val`, or `None`. - **cost**: O(log n) - **ties**: none: values are distinct - **traps**: never Examples: - `let (domain C, xs) = compress([10, 30]); xs.last_le(20) == Some(C.first!)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L827) ### `Compressed.last_lt` ```cp fn last_lt(self, val: T) -> ?D ``` The last index whose value is `< val`, or `None`. - **cost**: O(log n) - **ties**: none: values are distinct - **traps**: never Examples: - `let (domain C, xs) = compress([10, 30]); xs.last_lt(10) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L835) ## `Filtered` ```cp pub struct Filtered() ``` O(1) to make. The view `s.filter(p)`: walks `s`, skipping elements that fail `p`, with `s`'s keys. A lent value (R07.1.5). [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L1298) ### `Filtered.src` ```cp fn src(self) -> S ``` O(1). The source sequence this view filters. - **cost**: O(1) - **traps**: never Examples: - `let a = [1, 2]; a.filter(x => x > 1).src == a` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L1304) ## `Mapped` ```cp pub struct Mapped() ``` O(1) to make. The view `s.map(f)`: `f` of each element, with `s`'s keys; Indexed when `s` is. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L1307) ### `Mapped.src` ```cp fn src(self) -> S ``` O(1). The source sequence this view maps. - **cost**: O(1) - **traps**: never Examples: - `let a = [1, 2]; a.map(x => x * 2).src == a` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L1313) ## `Rev` ```cp pub struct Rev() ``` O(1) to make. The view `s.rev`: `s` walked backwards, keys unchanged. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L1316) ### `Rev.src` ```cp fn src(self) -> S ``` O(1). The source sequence this view reverses. - **cost**: O(1) - **traps**: never Examples: - `let a = [1, 2]; a.rev.src == a` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L1322) ## `Items` ```cp pub struct Items() ``` O(1) to make. The view `s.items`: `(key, element)` pairs in `s`'s order. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L1325) ### `Items.src` ```cp fn src(self) -> S ``` O(1). The source sequence whose items this view walks. - **cost**: O(1) - **traps**: never Examples: - `let a = [1, 2]; a.items.src == a` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L1331) ## `Slice` ```cp pub struct Slice() ``` O(1) to make. `s[r]`: a borrowed view of `s` over the range `r`. Every slice keeps its source's keys: `a[l..=r][i]` is `a[i]` and `i` must lie in `l..=r`; for a `List` or `Str`, `s[2..5][3]` is `s[3]` and `s[2..5][0]` traps. `w.first`, `w.nth(k)` and `w.rebase()` give offsets. Writable through a `var` source; the source's length can't change while it is alive. See `spec/core/04b-keys.md`. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L1338) ### `Slice.keys` ```cp fn keys(self) -> Range ``` O(1). The slice's keys: a sub-range of the source's keys. - **cost**: O(1) - **traps**: never - **order**: increasing Examples: - `[5, 6, 7][1..].keys == 1..3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L1345) ### `Slice.len` ```cp fn len(self) -> Int ``` - **cost**: O(1) - **traps**: never Examples: - `[1, 2, 3][1..].len == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L1351) ### `Slice.is_empty` ```cp fn is_empty(self) -> Bool ``` - **cost**: O(1) - **traps**: never Examples: - `[1, 2][2..].is_empty == true` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L1357) ### `Slice.iter` ```cp fn iter(self) -> yields Int ``` - **cost**: O(1) per step - **empty**: yields nothing - **order**: the slice's keys, increasing - **traps**: never Examples: - `[5, 6, 7][1..].iter().collect() == [1, 2]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L1365) ## `Rebased` ```cp pub struct Rebased(src ``` The view `rebase` returns. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L1424) ## `Keys` ```cp pub struct Keys(src: S, keys: I, by ``` The view `keyed` returns. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L1463) ## `SubseqStep` ```cp pub struct SubseqStep(items: List, pruned: Bool = false) ``` O(1). Steerable item yielded by `subsequences` (decision 126, W6). [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L2242) ### `SubseqStep.prune` ```cp fn prune(mut self) ``` O(1). Skip extending this prefix in the `subsequences` search tree. - **cost**: O(1) - **traps**: never Examples: - `[1, 2].subsequences().filter(s => s.items.len <= 1 or { s.prune(); false }).count() == 3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L2248) ## `OnlineLis` ```cp pub struct OnlineLis(strict: Bool = true) ``` O(1) construction; O(log n) push, O(1) amortized rollback. Online patience-sorting LIS tracker. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L2363) ### `OnlineLis.push` ```cp fn push(mut self, x: T) -> Int ``` O(log n). Append `x` and return the length of the longest increasing subsequence ending at `x`. - **cost**: O(log n) - **traps**: never Examples: - `var t = OnlineLis(); t.push(5); t.push(1); t.push(7) == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L2379) ### `OnlineLis.len` ```cp fn len(self) -> Int ``` O(1). Current global LIS length. - **cost**: O(1) - **traps**: never Examples: - `var t = OnlineLis(); t.push(1); t.push(3); t.len == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L2405) ### `OnlineLis.is_empty` ```cp fn is_empty(self) -> Bool ``` O(1). Whether no elements have been pushed. - **cost**: O(1) - **traps**: never Examples: - `OnlineLis().is_empty == true` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L2411) ### `OnlineLis.clear` ```cp fn clear(mut self) ``` O(1). Reset all state. - **cost**: O(1) - **traps**: never Examples: - `var t = OnlineLis(); t.push(1); t.clear(); t.len == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L2417) ### `OnlineLis.reconstruct` ```cp fn reconstruct(self) -> List ``` O(n), O(n) memory. Reconstruct one global LIS as 0-based push indices. - **cost**: O(n), O(n) memory - **empty**: `[]` - **ties**: the subsequence ending at the latest push of maximal length - **order**: increasing push indices - **traps**: never Examples: - `var t = OnlineLis(); for x in [3, 1, 2]: t.push(x); t.reconstruct() == [1, 2]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L2434) ### `OnlineLis.mark` ```cp fn mark(self) -> Int ``` O(1). Save a rollback checkpoint for DFS-on-tree LIS. - **cost**: O(1) - **traps**: never Examples: - `var t = OnlineLis(); let m = t.mark(); t.push(1); t.undo_to(m); t.len == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L2449) ### `OnlineLis.undo_to` ```cp fn undo_to(mut self, m: Int) ``` O(1) amortized. Roll back all `push`es since checkpoint `m`. - **cost**: O(1) amortized per undone push - **traps**: when `m` is not a live mark of this tracker Examples: - `var t = OnlineLis(); t.push(2); let m = t.mark(); t.push(5); t.undo_to(m); t.len == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L2455) ## `MonoStack` ```cp pub struct MonoStack(keep_smaller: Bool = true, strict: Bool = true) ``` O(1) construction; O(1) amortized push and rollback. Online monotone stack returning nearest dominating index. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L2472) ### `MonoStack.pops` ```cp fn pops(self, top: T, x: T) -> Bool ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L2480) ### `MonoStack.push` ```cp fn push(mut self, i: D, x: T) -> ?D ``` O(1) amortized. Push `(i, x)`, pop dominated entries, and return the nearest dominating index (or `None`). - **cost**: O(1) amortized - **ties**: equal values pop unless `strict: false` - **traps**: never Examples: - `var s = MonoStack(); s.push(0, 5); s.push(1, 3) == Some(0)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L2490) ### `MonoStack.top` ```cp fn top(self) -> ?(index: D, val: T) ``` O(1). Current top `(index, val)`, or `None` when empty. - **cost**: O(1) - **traps**: never - **ties**: none: the stack has one top Examples: - `var s = MonoStack(); s.push(3, 8); s.top == Some((index: 3, val: 8))` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L2507) ### `MonoStack.len` ```cp fn len(self) -> Int ``` O(1). Current stack depth. - **cost**: O(1) - **traps**: never Examples: - `var s = MonoStack(); s.push(0, 5); s.len == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L2514) ### `MonoStack.is_empty` ```cp fn is_empty(self) -> Bool ``` O(1). Whether the stack is empty. - **cost**: O(1) - **traps**: never Examples: - `MonoStack().is_empty == true` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L2520) ### `MonoStack.clear` ```cp fn clear(mut self) ``` O(1). Empty the stack and rollback log. - **cost**: O(1) - **traps**: never Examples: - `var s = MonoStack(); s.push(0, 1); s.clear(); s.is_empty` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L2526) ### `MonoStack.mark` ```cp fn mark(self) -> Int ``` O(1). Save a rollback checkpoint for DFS-on-tree monotone stacks. - **cost**: O(1) - **traps**: never Examples: - `var s = MonoStack(); let m = s.mark(); s.push(0, 1); s.undo_to(m); s.is_empty` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L2537) ### `MonoStack.undo_to` ```cp fn undo_to(mut self, m: Int) ``` O(1) amortized. Roll back all `push`es since checkpoint `m`. - **cost**: O(1) amortized per undone push - **traps**: when `m` is not a live mark of this stack Examples: - `var s = MonoStack(); s.push(0, 5); let m = s.mark(); s.push(1, 9); s.undo_to(m); s.len == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L2543) ## `Anchor` ```cp pub enum Anchor = Start | End ``` Which end of a piece a two-pointer result is keyed by. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L2970) ### `Anchor.Start` ```cp Start ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L2970) ### `Anchor.End` ```cp End ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L2970) ## `Ring` ```cp pub struct Ring(src: [D]T) ``` `a.ring`; see `ring`. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L3054) ### `Ring.step` ```cp fn step(self, i: D, d: Int) -> D ``` The position `d` steps after `i` (before it when `d < 0`), wrapping: a forced-online decode `(v + last - 1) % n + 1` is `V.ring.step(v, last)`. O(1). - **cost**: O(1) - **traps**: never Examples: - `[1, 2, 3].ring.step(0, -1) == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L3061) ### `Ring.next` ```cp fn next(self, i: D) -> D ``` The position after `i`, wrapping. - **cost**: O(1) - **traps**: never Examples: - `[1, 2, 3].ring.next(2) == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L3068) ### `Ring.prev` ```cp fn prev(self, i: D) -> D ``` The position before `i`, wrapping. - **cost**: O(1) - **traps**: never Examples: - `[1, 2, 3].ring.prev(0) == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L3075) ### `Ring.from` ```cp fn from(self, i: D) -> yields D ``` All n positions, starting at `i` and wrapping. O(n) to walk. - **cost**: O(1) per step - **empty**: yields nothing on an empty ring - **order**: `i`, then each next position, n in all - **traps**: never Examples: - `[1, 2, 3].ring.from(1).collect() == [1, 2, 0]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L3084) ### `Ring.span` ```cp fn span(self, start: D, len: Int) -> RingRange ``` The `len` positions from `start` on, wrapping (`len <= n`). - **cost**: O(1) - **empty**: an empty span when `len == 0` - **traps**: when `len` is not in `0..=n` Examples: - `[1, 2, 3].ring.span(2, 2).end == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L3093) ### `Ring.windows` ```cp fn windows(self, k: Int) -> yields RingSlice ``` The n windows of `k` elements, one starting at each position, wrapping. O(n) to walk. - **cost**: O(1) per window - **empty**: yields nothing - **order**: by start position, increasing - **traps**: when `k` is not in `1..=n` Examples: - `[1, 2, 3].ring.windows(2).count() == 3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L3104) ### `Ring.maximal` ```cp fn maximal(self, state: St, ok: St -> Bool) -> [D]RingSlice ``` Two pointers round the cycle: for each position as the last element, the longest wrapping piece (at most n elements) ending there that is `ok`, fed through `state: Track`. O(n) pushes and pops (two laps). - **cost**: O(n) pushes and pops on `state` - **empty**: an empty array - **order**: keyed by `D`, by last element - **traps**: never - **ties**: none: each last element has one longest piece Examples: - `[1, 1, 2].ring.maximal(state: Counter(0), ok: c => c.len <= 2).map(w => w.len) == [3, 3, 3]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L3118) ### `Ring.minimal` ```cp fn minimal(self, state: St, ok: St -> Bool) -> [D]?RingSlice ``` For each position as the last element, the shortest wrapping piece ending there that is `ok`, or None. O(n) pushes and pops (two laps). - **cost**: O(n) pushes and pops on `state` - **empty**: an empty array - **order**: keyed by `D`, by last element - **traps**: never - **ties**: none: each last element has one shortest piece Examples: - `[2, 0, 1].ring.minimal(state: Window(+), ok: w => (w.all ?? 0) >= 3).map(w => w.map(.len)) == [Some(2), Some(3), Some(3)]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L3129) ## `RingRange` ```cp pub struct RingRange() ``` A run of positions of `D` read cyclically, possibly wrapping past the last position, at most `D.count` of them. The keys-only half of a `RingSlice`, so it needs no array. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L3133) ### `RingRange.len` ```cp fn len(self) -> Int ``` - **cost**: O(1) - **traps**: never Examples: - `[1, 2, 3].ring.span(2, 2).len == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L3142) ### `RingRange.start` ```cp fn start(self) -> D ``` O(1). The first position. - **cost**: O(1) - **traps**: never Examples: - `[1, 2, 3].ring.span(2, 2).start == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L3149) ### `RingRange.end` ```cp fn end(self) -> D ``` O(1). The last position. - **cost**: O(1) - **traps**: on an empty span Examples: - `[1, 2, 3].ring.span(2, 2).end == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L3156) ### `RingRange.keys` ```cp fn keys(self) -> yields D ``` O(1) to make. Its positions in ring order. - **cost**: O(1) to make, O(1) per step - **order**: ring order from `start` - **traps**: never Examples: - `[1, 2, 3].ring.span(2, 2).keys.collect() == [2, 0]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L3164) ### `RingRange.contains` ```cp fn contains(self, i: D) -> Bool ``` - **cost**: O(1) - **traps**: never Examples: - `[1, 2, 3].ring.span(2, 2).contains(0) == true` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L3172) ## `RingSlice` ```cp pub struct RingSlice() ``` A contiguous piece of a ring, possibly wrapping past the end, at most n elements. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L3177) ### `RingSlice.range` ```cp fn range(self) -> RingRange ``` O(1). Its positions, without the array. - **cost**: O(1) - **traps**: never Examples: - `[1, 2, 3].ring.windows(2).first!.range.len == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L3185) ### `RingSlice.len` ```cp fn len(self) -> Int ``` - **cost**: O(1) - **traps**: never Examples: - `[w.len for w in [1, 2, 3].ring.windows(2)] == [2, 2, 2]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L3192) ### `RingSlice.start` ```cp fn start(self) -> D ``` O(1). The first position. - **cost**: O(1) - **traps**: never Examples: - `[1, 2, 3].ring.windows(2).first!.start == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L3199) ### `RingSlice.end` ```cp fn end(self) -> D ``` O(1). The last position. - **cost**: O(1) - **traps**: never Examples: - `[1, 2, 3].ring.windows(2).first!.end == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L3206) ### `RingSlice.keys` ```cp fn keys(self) -> yields D ``` O(1) to make. Its positions in ring order. - **cost**: O(1) to make, O(1) per step - **order**: ring order from `start` - **traps**: never Examples: - `[1, 2, 3].ring.windows(2).first!.keys.collect() == [0, 1]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/seq.cp#L3214) --- # slope URL: /docs/ref/std/slope Generated from [spec/std/slope.cp](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/slope.cp) by `cpl doc --format json`. ## `Concave` ```cp pub struct Concave(start: Int, base: Int) ``` O(log n) expected per slope operation, for n slopes. A concave function on the integers `lo..=hi`: its value at `lo` and its slopes in falling order. Law: every operation keeps it concave. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/slope.cp#L19) ### `Concave.point` ```cp fn point(d: Int) -> Concave ``` The function defined on the single point `d`, with `f(d) = 0`. - **cost**: O(1) - **traps**: never Examples: - `Concave.point(3).at(3) == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/slope.cp#L27) ### `Concave.flat` ```cp fn flat(r: Range) -> Concave ``` The function that is 0 on every point of `r`; its domain is `r`, so `lo` is the first point of `r` and `hi` the last. - **cost**: O(|r| log |r|) expected - **empty**: traps - **traps**: when `r` is empty Examples: - `let f = Concave.flat(2..5); f.lo == 2 and f.hi == 4` - `var f = Concave.flat(0..=1); f.max() == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/slope.cp#L37) ### `Concave.reserve` ```cp fn reserve(mut self, n: Int) ``` Make room for `n` slopes in total, so later operations do not regrow the storage. Changes no value. - **cost**: O(n) - **traps**: when `n < 0` Examples: - `var f = Concave.flat(0..=3); f.reserve(100); f.at(2) == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/slope.cp#L48) ### `Concave.lo` ```cp fn lo(self) -> Int ``` The first point of the domain. - **cost**: O(1) - **traps**: never Examples: - `var f = Concave.flat(0..=3); f.shift(-2); f.lo == -2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/slope.cp#L55) ### `Concave.hi` ```cp fn hi(self) -> Int ``` The last point of the domain. - **cost**: O(1) - **traps**: never Examples: - `var f = Concave.flat(0..=3); f.max_convolve(Concave.flat(0..=2)); f.hi == 5` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/slope.cp#L62) ### `Concave.max_convolve` ```cp fn max_convolve(mut self, g: Concave) ``` Replace `f` with `c => max over a + b == c of f(a) + g(b)`. The domain becomes `lo + g.lo ..= hi + g.hi` and the two slope multisets merge, so the result stays concave. Pass the smaller function as `g`: the cost is in its size. - **cost**: O(|g| log n) expected, for `|g|` slopes in `g` - **ties**: only the value is kept; which point attains it does not matter - **traps**: never Examples: - `var f = Concave.point(0); f.add_const(3); f.max_convolve(Concave.flat(0..=2)); f.hi == 2 and f.at(1) == 3` - `var f = Concave.flat(0..=2); f.add_abs(1); var g = Concave.flat(0..=1); g.add_linear(-5); f.max_convolve(g); f.at(3) == -6` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/slope.cp#L73) ### `Concave.add_quadratic` ```cp fn add_quadratic(mut self, q: Int -> Int) ``` `f(c) += q(c)` for a quadratic `q` with leading coefficient at most 0, so `f` stays concave. `q` is called at most four times: three points fix it and a fourth checks that it is quadratic. - **cost**: O(1) - **traps**: when `q` is not a quadratic polynomial on the points read, or its leading coefficient is positive Examples: - `var f = Concave.flat(0..=3); f.add_quadratic(x => -x * x + 1); f.at(2) == -3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/slope.cp#L85) ### `Concave.at` ```cp fn at(mut self, c: Int) -> Int ``` The value `f(c)`. - **cost**: O(log n) expected (O(c - lo + log n) in the current implementation) - **traps**: when `c` is outside `lo..=hi` Examples: - `var f = Concave.flat(0..=4); f.add_abs(1); f.at(4) == -3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/slope.cp#L98) ### `Concave.max` ```cp fn max(mut self) -> Int ``` The largest value of `f` over its domain. - **cost**: O(log n) expected (O(n) in the current implementation) - **ties**: only the value is kept; which point attains it does not matter - **traps**: never Examples: - `var f = Concave.flat(0..=4); f.add_abs(1); f.add_const(5); f.max() == 5` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/slope.cp#L108) ### `Concave.add_left` ```cp fn add_left(mut self, a: Int) ``` Add `min(0, x - a)`: a hinge with slope 1 left of `a` and flat from `a` on. - **cost**: O(log n) expected - **traps**: never Examples: - `var f = Concave.flat(0..=4); f.add_left(2); f.at(0) == -2 and f.at(3) == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/slope.cp#L120) ### `Concave.add_right` ```cp fn add_right(mut self, a: Int) ``` Add `min(0, a - x)`: flat up to `a` and slope -1 right of it. - **cost**: O(log n) expected - **traps**: never Examples: - `var f = Concave.flat(0..=4); f.add_right(2); f.at(4) == -2 and f.at(1) == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/slope.cp#L129) ### `Concave.add_abs` ```cp fn add_abs(mut self, a: Int) ``` Add `-|x - a|`; `add_left(a)` and `add_right(a)` together. - **cost**: O(log n) expected - **traps**: never Examples: - `var f = Concave.flat(0..=4); f.add_abs(1); f.at(0) == -1 and f.at(4) == -3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/slope.cp#L138) ### `Concave.add_const` ```cp fn add_const(mut self, c: Int) ``` Add the constant `c` everywhere. - **cost**: O(1) - **traps**: never Examples: - `var f = Concave.point(2); f.add_const(-4); f.at(2) == -4` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/slope.cp#L146) ### `Concave.add_linear` ```cp fn add_linear(mut self, k: Int) ``` Add `k * x`, applied lazily to every slope. - **cost**: O(1) - **traps**: never Examples: - `var f = Concave.flat(0..=4); f.add_linear(2); f.at(3) == 6 and f.at(0) == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/slope.cp#L153) ### `Concave.prefix_max` ```cp fn prefix_max(mut self) ``` Replace `f(x)` with the largest `f(y)` over `y <= x` in the domain; the domain is unchanged and every falling slope becomes 0. - **cost**: O(log n) expected (O(n log n) in the current implementation) - **ties**: only the value is kept; which point attains it does not matter - **traps**: never Examples: - `var f = Concave.flat(0..=4); f.add_abs(2); f.prefix_max(); f.at(0) == -2 and f.at(4) == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/slope.cp#L163) ### `Concave.suffix_max` ```cp fn suffix_max(mut self) ``` Replace `f(x)` with the largest `f(y)` over `y >= x` in the domain; the domain is unchanged and every rising slope becomes 0. - **cost**: O(log n) expected (O(n log n) in the current implementation) - **ties**: only the value is kept; which point attains it does not matter - **traps**: never Examples: - `var f = Concave.flat(0..=4); f.add_abs(2); f.suffix_max(); f.at(0) == 0 and f.at(4) == -2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/slope.cp#L175) ### `Concave.shift` ```cp fn shift(mut self, d: Int) ``` Move the function right by `d`: the new `f(x)` is the old `f(x - d)`, and `lo` and `hi` both grow by `d`. - **cost**: O(1) - **traps**: never Examples: - `var f = Concave.point(0); f.add_const(7); f.shift(5); f.lo == 5 and f.at(5) == 7` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/slope.cp#L186) ### `Concave.slide_max` ```cp fn slide_max(mut self, a: Int, b: Int) ``` Replace `f(x)` with the largest old `f(y)` over `x - b <= y <= x - a`; the domain becomes `lo + a ..= hi + b`. The same as `max_convolve(Concave.flat(a..=b))`. - **cost**: O(b - a + log n) expected - **ties**: only the value is kept; which point attains it does not matter - **traps**: when `a > b` Examples: - `var f = Concave.point(0); f.add_const(1); f.slide_max(-1, 2); f.lo == -1 and f.hi == 2 and f.at(2) == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/slope.cp#L195) ### `Concave.argmax` ```cp fn argmax(mut self) -> Range ``` The points where `f` reaches its maximum, as a half-open range; by concavity they are contiguous. - **cost**: O(log n) expected (O(n) in the current implementation) - **order**: ascending points - **ties**: every maximizing point is included - **traps**: never Examples: - `var f = Concave.flat(0..=4); f.add_abs(2); f.argmax() == 2..3` - `Concave.flat(0..=4).argmax() == 0..5` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/slope.cp#L208) ### `Concave.count_at_least` ```cp fn count_at_least(self, v: Int) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/slope.cp#L211) ## `Convex` ```cp pub struct Convex(neg: Concave) ``` O(log n) expected per slope operation, for n slopes. A convex function on the integers `lo..=hi`, the negation of a `Concave`: the same operations with `min` for `max`. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/slope.cp#L221) ### `Convex.point` ```cp fn point(d: Int) -> Convex ``` The function defined on the single point `d`, with `f(d) = 0`. - **cost**: O(1) - **traps**: never Examples: - `Convex.point(3).at(3) == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/slope.cp#L227) ### `Convex.flat` ```cp fn flat(r: Range) -> Convex ``` The function that is 0 on every point of `r`; its domain is `r`. - **cost**: O(|r| log |r|) expected - **empty**: traps - **traps**: when `r` is empty Examples: - `let f = Convex.flat(2..5); f.lo == 2 and f.hi == 4` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/slope.cp#L235) ### `Convex.lo` ```cp fn lo(self) -> Int ``` The first point of the domain. - **cost**: O(1) - **traps**: never Examples: - `var f = Convex.flat(0..=3); f.shift(-2); f.lo == -2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/slope.cp#L242) ### `Convex.hi` ```cp fn hi(self) -> Int ``` The last point of the domain. - **cost**: O(1) - **traps**: never Examples: - `var f = Convex.flat(0..=3); f.min_convolve(Convex.flat(0..=2)); f.hi == 5` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/slope.cp#L249) ### `Convex.min_convolve` ```cp fn min_convolve(mut self, g: Convex) ``` Replace `f` with `c => min over a + b == c of f(a) + g(b)`. The domain becomes `lo + g.lo ..= hi + g.hi` and the slope multisets merge. Pass the smaller function as `g`. - **cost**: O(|g| log n) expected, for `|g|` slopes in `g` - **ties**: only the value is kept; which point attains it does not matter - **traps**: never Examples: - `var f = Convex.point(0); f.add_const(3); f.min_convolve(Convex.flat(0..=2)); f.hi == 2 and f.at(1) == 3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/slope.cp#L258) ### `Convex.add_quadratic` ```cp fn add_quadratic(mut self, q: Int -> Int) ``` `f(c) += q(c)` for a quadratic `q` with leading coefficient at least 0, so `f` stays convex; `q` is called at most four times, as in `Concave.add_quadratic`. - **cost**: O(1) - **traps**: when `q` is not a quadratic polynomial on the points read, or its leading coefficient is negative Examples: - `var f = Convex.flat(0..=3); f.add_quadratic(x => x * x); f.at(3) == 9` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/slope.cp#L266) ### `Convex.at` ```cp fn at(mut self, c: Int) -> Int ``` The value `f(c)`. - **cost**: O(log n) expected (O(c - lo + log n) in the current implementation) - **traps**: when `c` is outside `lo..=hi` Examples: - `var f = Convex.flat(0..=4); f.add_abs(1); f.at(4) == 3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/slope.cp#L273) ### `Convex.min` ```cp fn min(mut self) -> Int ``` The smallest value of `f` over its domain. - **cost**: O(log n) expected (O(n) in the current implementation) - **ties**: only the value is kept; which point attains it does not matter - **traps**: never Examples: - `var f = Convex.flat(0..=4); f.add_abs(1); f.add_const(5); f.min() == 5` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/slope.cp#L281) ### `Convex.add_left` ```cp fn add_left(mut self, a: Int) ``` Add `max(0, a - x)`: slope -1 left of `a` and flat from `a` on. - **cost**: O(log n) expected - **traps**: never Examples: - `var f = Convex.flat(0..=4); f.add_left(2); f.at(0) == 2 and f.at(3) == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/slope.cp#L288) ### `Convex.add_right` ```cp fn add_right(mut self, a: Int) ``` Add `max(0, x - a)`: flat up to `a` and slope 1 right of it. - **cost**: O(log n) expected - **traps**: never Examples: - `var f = Convex.flat(0..=4); f.add_right(2); f.at(4) == 2 and f.at(1) == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/slope.cp#L294) ### `Convex.add_abs` ```cp fn add_abs(mut self, a: Int) ``` Add `|x - a|`; `add_left(a)` and `add_right(a)` together. - **cost**: O(log n) expected - **traps**: never Examples: - `var f = Convex.flat(0..=4); f.add_abs(1); f.at(0) == 1 and f.at(4) == 3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/slope.cp#L300) ### `Convex.add_const` ```cp fn add_const(mut self, c: Int) ``` Add the constant `c` everywhere. - **cost**: O(1) - **traps**: never Examples: - `var f = Convex.point(2); f.add_const(-4); f.at(2) == -4` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/slope.cp#L306) ### `Convex.add_linear` ```cp fn add_linear(mut self, k: Int) ``` Add `k * x`, applied lazily to every slope. - **cost**: O(1) - **traps**: never Examples: - `var f = Convex.flat(0..=4); f.add_linear(-2); f.at(3) == -6` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/slope.cp#L312) ### `Convex.prefix_min` ```cp fn prefix_min(mut self) ``` Replace `f(x)` with the smallest `f(y)` over `y <= x` in the domain; the domain is unchanged. - **cost**: O(log n) expected (O(n log n) in the current implementation) - **ties**: only the value is kept; which point attains it does not matter - **traps**: never Examples: - `var f = Convex.flat(0..=4); f.add_abs(2); f.prefix_min(); f.at(0) == 2 and f.at(4) == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/slope.cp#L319) ### `Convex.suffix_min` ```cp fn suffix_min(mut self) ``` Replace `f(x)` with the smallest `f(y)` over `y >= x` in the domain; the domain is unchanged. - **cost**: O(log n) expected (O(n log n) in the current implementation) - **ties**: only the value is kept; which point attains it does not matter - **traps**: never Examples: - `var f = Convex.flat(0..=4); f.add_abs(2); f.suffix_min(); f.at(0) == 0 and f.at(4) == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/slope.cp#L326) ### `Convex.shift` ```cp fn shift(mut self, d: Int) ``` Move the function right by `d`: the new `f(x)` is the old `f(x - d)`, and `lo` and `hi` both grow by `d`. - **cost**: O(1) - **traps**: never Examples: - `var f = Convex.point(0); f.add_const(7); f.shift(5); f.lo == 5 and f.at(5) == 7` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/slope.cp#L333) ### `Convex.slide_min` ```cp fn slide_min(mut self, a: Int, b: Int) ``` Replace `f(x)` with the smallest old `f(y)` over `x - b <= y <= x - a`; the domain becomes `lo + a ..= hi + b`. The same as `min_convolve(Convex.flat(a..=b))`. - **cost**: O(b - a + log n) expected - **ties**: only the value is kept; which point attains it does not matter - **traps**: when `a > b` Examples: - `var f = Convex.point(0); f.add_const(1); f.slide_min(-1, 2); f.lo == -1 and f.hi == 2 and f.at(-1) == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/slope.cp#L341) ### `Convex.argmin` ```cp fn argmin(mut self) -> Range ``` The points where `f` reaches its minimum, as a half-open range; by convexity they are contiguous. - **cost**: O(log n) expected (O(n) in the current implementation) - **order**: ascending points - **ties**: every minimizing point is included - **traps**: never Examples: - `var f = Convex.flat(0..=4); f.add_abs(2); f.argmin() == 2..3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/slope.cp#L350) --- # sparse URL: /docs/ref/std/sparse Generated from [spec/std/sparse.cp](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/sparse.cp) by `cpl doc --format json`. ## `SparseTable` ```cp pub struct SparseTable(op: (T, T) -> T) ``` `SparseTable(min, a)`: built in O(n log n) time and memory, `fold` is O(1). The operation must be associative and idempotent (`op(a, a) == a`): `min`, `max`, `gcd`, `&`, `|`, or any custom `(T, T) -> T` — no identity is required because `fold` asserts the range is non-empty and returns `T` directly. Sums are not idempotent; use `Fenwick` or `prefix` for those. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/sparse.cp#L9) ### `SparseTable.new` ```cp fn new(op: (T, T) -> T, a: [D]T) -> SparseTable ``` Build a sparse table for the idempotent, associative `op` over the values of `a`. Level `k` holds the fold of every window of length `2^k`, so any non-empty range is the fold of two overlapping windows. The table copies `a` and keeps its domain `D`. - **cost**: O(|D| log |D|) time and memory, `op` called O(|D| log |D|) times - **empty**: an empty `a` builds an empty table; every `fold` on it traps, `try_fold` is `None` - **order**: the table keeps the domain `D` of `a` - **traps**: never (a non-idempotent or non-associative `op` gives unspecified folds; check with `idempotent`) Examples: - `SparseTable(min, [3, 1, 4]).fold(0..3) == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/sparse.cp#L22) ### `SparseTable.fold` ```cp fn fold(self, r: Range) -> T ``` The fold of `op` over the positions of the non-empty range `r`, as two overlapping power-of-two windows combined with one `op` call. - **cost**: O(1) - **empty**: traps; use `try_fold` when `r` may be empty - **traps**: when `r` is empty or reaches outside `D` Examples: - `SparseTable(max, [3, 1, 4]).fold(0..2) == 3` - `SparseTable(min, [3, 1, 4]).fold(1..2) == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/sparse.cp#L53) ### `SparseTable.try_fold` ```cp fn try_fold(self, r: Range) -> ?T ``` The fold of `r` like `fold`, or `None` when `r` is empty. - **cost**: O(1) - **empty**: `None` - **traps**: when a non-empty `r` reaches outside `D` Examples: - `SparseTable(min, [3, 1, 4]).try_fold(1..1) == None` - `SparseTable(min, [3, 1, 4]).try_fold(1..3) == Some(1)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/sparse.cp#L68) ### `SparseTable.get` ```cp fn get(self, i: D) -> T ``` The original value at position `i` (level 0 of the table). - **cost**: O(1) - **traps**: when `i` is outside `D` Examples: - `SparseTable(min, [3, 1, 4]).get(2) == 4` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/sparse.cp#L77) ### `SparseTable.all` ```cp fn all(self) -> T ``` The fold of every position of `D`; `fold(D.all)`. - **cost**: O(1) - **empty**: traps on an empty domain - **traps**: when `D` is empty Examples: - `SparseTable(gcd, [4, 6, 10]).all == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/sparse.cp#L86) ## `DisjointSparseTable` ```cp pub struct DisjointSparseTable(op: (T, T) -> T) ``` Disjoint sparse table: O(n log n) build and memory, O(1) range fold for ANY associative operation — no idempotence and no inverse required (matrix products, `Mod

` products, `MaxSub`, string concatenation). Asserts `not r.is_empty`. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/sparse.cp#L109) ### `DisjointSparseTable.new` ```cp fn new(op: (T, T) -> T, a: [D]T) -> DisjointSparseTable ``` Build a disjoint sparse table for the associative `op` over `a`. Each level splits the domain into blocks and stores folds outward from each block's middle, so a range is answered by combining one suffix fold and one prefix fold; no idempotence, identity or inverse is needed. - **cost**: O(|D| log |D|) time and memory, `op` called O(|D| log |D|) times - **empty**: an empty `a` builds an empty table; every `fold` on it traps, `try_fold` is `None` - **order**: the table keeps the domain `D` of `a`; folds run in domain order - **traps**: never (a non-associative `op` gives unspecified folds) Examples: - `DisjointSparseTable((a, b) => a + b, [3, 1, 4]).fold(0..3) == 8` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/sparse.cp#L122) ### `DisjointSparseTable.fold` ```cp fn fold(self, r: Range) -> T ``` The fold of `op` over the non-empty range `r`, left to right in domain order, so a non-commutative `op` sees its operands in position order. - **cost**: O(1), at most one `op` call - **empty**: traps; use `try_fold` when `r` may be empty - **traps**: when `r` is empty or reaches outside `D` Examples: - `DisjointSparseTable((a, b) => a + b, [3, 1, 4]).fold(1..3) == 5` - `DisjointSparseTable((a, b) => a, [7, 8, 9]).fold(1..3) == 8` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/sparse.cp#L163) ### `DisjointSparseTable.try_fold` ```cp fn try_fold(self, r: Range) -> ?T ``` The fold of `r` like `fold`, or `None` when `r` is empty. - **cost**: O(1) - **empty**: `None` - **traps**: when a non-empty `r` reaches outside `D` Examples: - `DisjointSparseTable((a, b) => a + b, [3, 1, 4]).try_fold(2..2) == None` - `DisjointSparseTable((a, b) => a + b, [3, 1, 4]).try_fold(0..2) == Some(4)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/sparse.cp#L181) ### `DisjointSparseTable.get` ```cp fn get(self, i: D) -> T ``` The original value at position `i`. - **cost**: O(1) - **traps**: when `i` is outside `D` Examples: - `DisjointSparseTable((a, b) => a + b, [3, 1, 4]).get(0) == 3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/sparse.cp#L190) ### `DisjointSparseTable.all` ```cp fn all(self) -> T ``` The fold of every position of `D`, left to right; `fold(D.all)`. - **cost**: O(1) - **empty**: traps on an empty domain - **traps**: when `D` is empty Examples: - `DisjointSparseTable((a, b) => a + b, [3, 1, 4]).all == 8` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/sparse.cp#L199) ## `SparseTable2D` ```cp pub struct SparseTable2D(op: (T, T) -> T) ``` O(|R| * |C| * log |R| * log |C|) build and memory; O(1) rectangle fold for any associative, idempotent operation (`min`, `max`, `gcd`, `&`, `|`). [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/sparse.cp#L210) ### `SparseTable2D.at` ```cp fn at(self, kr: Int, kc: Int, i: Int, j: Int) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/sparse.cp#L217) ### `SparseTable2D.new` ```cp fn new(op: (T, T) -> T, a: [R, C]T) -> SparseTable2D ``` Build a 2-D sparse table for the idempotent, associative `op` over the grid `a`: one `SparseTable` level per power-of-two row height and column width. Keeps the domains `R`, `C`. - **cost**: O(|R| |C| log |R| log |C|) time and memory - **empty**: an empty grid builds an empty table; every `fold` on it traps - **order**: the table keeps the domains `R` and `C` of `a` - **traps**: never (a non-idempotent `op` gives unspecified folds) Examples: - `SparseTable2D(max, [2, 2] (r, c) => r * 2 + c).fold(0..2, 0..2) == 3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/sparse.cp#L227) ### `SparseTable2D.fold` ```cp fn fold(self, rows: Range, cols: Range) -> T ``` The fold of `op` over the rectangle `rows` by `cols`, both non-empty: four overlapping power-of-two blocks combined with `op`. - **cost**: O(1) - **empty**: traps when either range is empty; use `try_fold` - **traps**: when either range is empty or reaches outside its domain Examples: - `SparseTable2D(min, [2, 2] (r, c) => r * 2 + c).fold(1..2, 0..2) == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/sparse.cp#L252) ### `SparseTable2D.try_fold` ```cp fn try_fold(self, rows: Range, cols: Range) -> ?T ``` The rectangle fold like `fold`, or `None` when `rows` or `cols` is empty. - **cost**: O(1) - **empty**: `None` when either range is empty - **traps**: when a range reaches outside its domain on a non-empty rectangle Examples: - `SparseTable2D(min, [2, 2] (r, c) => r * 2 + c).try_fold(0..2, 1..1) == None` - `SparseTable2D(min, [2, 2] (r, c) => r * 2 + c).try_fold(0..2, 1..2) == Some(1)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/sparse.cp#L267) ### `SparseTable2D.get` ```cp fn get(self, r: R, c: C) -> T ``` The original cell value `a[r, c]`. - **cost**: O(1) - **traps**: when `r` is outside `R` or `c` is outside `C` Examples: - `SparseTable2D(min, [2, 2] (r, c) => r * 2 + c).get(1, 0) == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/sparse.cp#L277) ## `LinearRmq` ```cp pub struct LinearRmq(before: (T, T) -> Bool) ``` O(|D|) build and memory; O(1) range min/max query via block-of-64 bitmask RMQ (Four Russians). Useful for O(1) LCA and memory-tight static RMQ where O(n log n) space is too large. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/sparse.cp#L282) ### `LinearRmq.better` ```cp fn better(self, i: Int, j: Int) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/sparse.cp#L289) ### `LinearRmq.in_block` ```cp fn in_block(self, l: Int, r: Int) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/sparse.cp#L291) ### `LinearRmq.new` ```cp fn new(a: [D]T, before: (T, T) -> Bool = (x, y) => x < y) -> LinearRmq ``` Build a linear-space range-best structure over `a`, where `before(x, y)` means `x` is better than `y` (default `<`, so the best is the minimum). Blocks of 64 positions carry a sparse table over block bests and an in-block bitmask stack, so queries never scan. - **cost**: O(|D|) time and memory - **empty**: an empty `a` builds an empty structure; `argbest` and `best` on it trap - **order**: the structure keeps the domain `D` of `a` - **traps**: never (`before` must be a strict weak order, or results are unspecified) Examples: - `LinearRmq([3, 1, 4]).best(0..3) == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/sparse.cp#L305) ### `LinearRmq.argbest` ```cp fn argbest(self, r: Range) -> D ``` The position of the best element of the non-empty range `r` under `before`; the leftmost when several are equally best (neither is `before` the other). - **cost**: O(1) - **empty**: traps - **ties**: the first in key order - **traps**: when `r` is empty or reaches outside `D` Examples: - `LinearRmq([3, 1, 1, 4]).argbest(0..4) == 1` - `LinearRmq([3, 1, 4], before: (x, y) => x > y).argbest(0..3) == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/sparse.cp#L334) ### `LinearRmq.best` ```cp fn best(self, r: Range) -> T ``` The value of the best element of the non-empty range `r` under `before`; `a[argbest(r)]`. - **cost**: O(1) - **empty**: traps; use `try_best` when `r` may be empty - **ties**: equal-best values are interchangeable; the value at the leftmost is returned - **traps**: when `r` is empty or reaches outside `D` Examples: - `LinearRmq([3, 1, 4], before: (x, y) => x > y).best(0..3) == 4` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/sparse.cp#L353) ### `LinearRmq.try_best` ```cp fn try_best(self, r: Range) -> ?T ``` The value of the best element of `r` like `best`, or `None` when `r` is empty. - **cost**: O(1) - **empty**: `None` - **ties**: the value at the leftmost equal-best position - **traps**: when a non-empty `r` reaches outside `D` Examples: - `LinearRmq([3, 1]).try_best(1..1) == None` - `LinearRmq([3, 1]).try_best(0..2) == Some(1)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/sparse.cp#L364) --- # strings URL: /docs/ref/std/strings Generated from [spec/std/strings.cp](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp) by `cpl doc --format json`. ## `KmpAutomaton` ```cp pub struct KmpAutomaton ``` O(|pat| * |A|). Prefix (KMP) automaton over alphabet domain `A`, for O(1) transitions in DP. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L652) ### `KmpAutomaton.new` ```cp fn new(pat: S) -> KmpAutomaton ``` The KMP automaton of `pat` over the alphabet domain `A`: one state per matched prefix length `0..=pat.len`, with a full transition table. Call it as `KmpAutomaton(pat)`. - **cost**: O(|pat| * |A|) - **empty**: an empty `pat` gives one state, `0`, which matches everywhere - **traps**: when an element of `pat` is not in `A` Examples: - `KmpAutomaton("aba").len == 4` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L665) ### `KmpAutomaton.len` ```cp fn len(self) -> Int ``` The number of states, `pat.len + 1`; the states are `0..=pat.len` and `pat.len` means a full match. - **cost**: O(1) - **traps**: never Examples: - `KmpAutomaton("ab").len == 3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L695) ### `KmpAutomaton.step` ```cp fn step(self, state: Int, a: A) -> Int ``` The matched prefix length after reading `a` in `state`. From the full-match state the automaton falls back along `link` first, so matching continues and overlaps are found. - **cost**: O(1) - **traps**: when `state` is outside `0..self.len` Examples: - `let k = KmpAutomaton("aba"); k.step(3, 'b') == 2 and k.step(0, 'b') == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L704) ### `KmpAutomaton.link` ```cp fn link(self, state: Int) -> Int ``` The failure link of `state`: the length of the longest proper border of `pat[..state]`, and `0` at state `0`. It equals `prefix_function(pat)[state - 1]` for `state >= 1`. - **cost**: O(1) - **traps**: when `state` is outside `0..self.len` Examples: - `let k = KmpAutomaton("aba"); k.link(3) == 1 and k.link(2) == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L717) ### `KmpAutomaton.find_all` ```cp fn find_all(self, text: S) -> yields Int ``` The start position (0-based, counted in `text`'s iteration order) of every occurrence of `pat` in `text`, overlapping ones included. - **cost**: O(|text|) - **empty**: an empty `text` yields nothing unless `pat` is empty; an empty `pat` yields `0..=|text|` - **ties**: every occurrence is yielded; None is preferred - **order**: increasing start - **traps**: when an element of `text` is not in `A` Examples: - `KmpAutomaton("aba").find_all("ababa").collect() == [0, 2]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L731) ## `Palindromes` ```cp pub struct Palindromes(odd: List, even: List) ``` O(n) space, O(1) queries. Manacher palindrome radii. `odd[i]` is the number of palindromes centred on `s[i]`; `even[i]` is the number centred between `s[i - 1]` and `s[i]`. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L793) ### `Palindromes.len` ```cp fn len(self) -> Int ``` The length of the sequence the radii were computed for. - **cost**: O(1) - **traps**: never Examples: - `manacher("aba").len == 3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L799) ### `Palindromes.is_empty` ```cp fn is_empty(self) -> Bool ``` True when the sequence the radii were computed for is empty. - **cost**: O(1) - **traps**: never Examples: - `manacher("").is_empty == true` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L806) ### `Palindromes.longest_at` ```cp fn longest_at(self, i: Int) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L809) ### `Palindromes.longest_between` ```cp fn longest_between(self, i: Int) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L819) ### `Palindromes.is_palindrome` ```cp fn is_palindrome(self, r: R) -> Bool ``` True when the positions `r` (`l..r`, `l..=r`, or a `Range`) of the original sequence form a palindrome: `p.is_palindrome(l..r) == is_palindrome(s[l..r])`. - **cost**: O(1) - **traps**: when `r` reaches outside `0..=self.len` Examples: - `let p = manacher("abacaba"); p.is_palindrome(0..3) and not p.is_palindrome(1..4)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L835) ### `Palindromes.count` ```cp fn count(self) -> Int ``` The number of non-empty palindromic substrings, each occurrence counted: `sum(odd) + sum(even)`. - **cost**: O(n) - **traps**: never Examples: - `manacher("aaa").count() == 6` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L851) ### `Palindromes.longest` ```cp fn longest(self) -> (l: Int, r: Int) ``` The half-open range `(l, r)` of a longest palindromic substring. - **cost**: O(n) - **ties**: the leftmost (smallest `l`) - **traps**: never Examples: - `manacher("abacdc").longest() == (0, 3)` - `manacher("").longest() == (0, 0)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L864) ## `SuffixArray` ```cp pub struct SuffixArray ``` O(n) SA-IS + Kasai LCP (O(n log n) with RMQ). Suffix array, inverse rank, adjacent LCP, and O(1) LCP/comparison queries. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L1062) ### `SuffixArray.new` ```cp fn new(s: S) -> SuffixArray ``` The suffix array of `s` with its inverse and LCP array: `sa[r]` is the start of the suffix of rank `r`, `rank[sa[r]] == r`, and `lcp[r]` is the LCP of the suffixes of ranks `r` and `r + 1`. Call it as `SuffixArray(s)`; positions count from 0. Elements are compared by `Ord`, so a shorter suffix that is a prefix of a longer one ranks first. - **cost**: O(n) for `Str` and small integer alphabets, O(n log n) otherwise - **empty**: `sa`, `rank` and `lcp` all empty - **traps**: never Examples: - `SuffixArray("banana").sa == [5, 3, 1, 0, 4, 2]` - `SuffixArray("banana").lcp == [1, 3, 0, 0, 2]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L1083) ### `SuffixArray.len` ```cp fn len(self) -> Int ``` The length `n` of the sequence the suffix array was built over. - **cost**: O(1) - **traps**: never Examples: - `SuffixArray("banana").len == 6` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L1129) ### `SuffixArray.is_empty` ```cp fn is_empty(self) -> Bool ``` True when the suffix array was built over an empty sequence. - **cost**: O(1) - **traps**: never Examples: - `SuffixArray("").is_empty == true` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L1136) ### `SuffixArray.lcp_between` ```cp fn lcp_between(self, i: Int, j: Int) -> Int ``` The length of the longest common prefix of the suffixes starting at `i` and `j`. The empty suffix at `n` is allowed, and `lcp_between(i, i) == n - i`. - **cost**: O(1) - **traps**: when `i` or `j` is outside `0..=self.len` Examples: - `SuffixArray("banana").lcp_between(1, 3) == 3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L1144) ### `SuffixArray.rank_range` ```cp fn rank_range(self, pat: P) -> Range ``` The ranks `lo..hi` of the suffixes that start with `pat`. When there are None it is the empty range at the rank where `pat` would sort. - **cost**: O(|pat| log n) - **empty**: an empty `pat` gives `0..n` - **order**: a range of ranks, increasing - **traps**: never Examples: - `SuffixArray("banana").rank_range("ana") == 1..3` - `SuffixArray("banana").rank_range("c") == 4..4` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L1161) ### `SuffixArray.find_all` ```cp fn find_all(self, pat: P) -> yields Int ``` The start of every occurrence of `pat`, read off `sa` over `rank_range(pat)`. - **cost**: O(|pat| log n + occurrences) - **empty**: an empty `pat` yields every start `0..n` (not the end position `n`) - **ties**: every occurrence is yielded; None is preferred - **order**: suffix-array order (by rank), not by position - **traps**: never Examples: - `SuffixArray("banana").find_all("ana").collect() == [3, 1]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L1202) ### `SuffixArray.count` ```cp fn count(self, pat: P) -> Int ``` The number of occurrences of `pat`, overlapping ones included: `rank_range(pat).len`. - **cost**: O(|pat| log n) - **empty**: an empty `pat` gives `n` - **traps**: never Examples: - `SuffixArray("banana").count("an") == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L1211) ### `SuffixArray.lcp_range` ```cp fn lcp_range(self, i: Int, len: Int) -> Range ``` The ranks `lo..hi` of the suffixes whose LCP with the suffix at `i` is at least `len`; always contains `rank[i]`. - **cost**: O(log n) - **order**: a range of ranks, increasing; it holds `rank[i]` - **traps**: when `i` is outside `0..n` or `len` outside `0..=n - i` Examples: - `SuffixArray("banana").lcp_range(1, 3) == 1..3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L1220) ### `SuffixArray.compare` ```cp fn compare(self, l1: Int, r1: Int, l2: Int, r2: Int) -> Int ``` The lexicographic comparison of `s[l1..r1]` and `s[l2..r2]`: `-1`, `0` or `1`. A proper prefix compares less. - **cost**: O(1) - **traps**: when a range is not within `0..=n` or has its end before its start Examples: - `SuffixArray("banana").compare(1, 3, 3, 5) == 0` - `SuffixArray("banana").compare(1, 2, 1, 3) == -1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L1242) ### `SuffixArray.arg_min` ```cp fn arg_min(self, lo: Int, hi: Int) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L1252) ### `SuffixArray.distinct` ```cp fn distinct(self) -> Int ``` The number of distinct non-empty substrings: `n * (n + 1) / 2 - sum(lcp)`. - **cost**: O(n) - **traps**: never Examples: - `SuffixArray("banana").distinct() == 15` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L1264) ### `SuffixArray.lcp_of_ranks` ```cp fn lcp_of_ranks(self, r: Range) -> Int ``` The longest prefix common to every suffix with rank in `r`: the minimum of `lcp[j]` for `j in r.start..r.end - 1`, or the suffix's own length when `r` holds one rank. - **cost**: O(1) - **empty**: an empty `r` traps - **traps**: when `r` is empty or reaches outside `0..n` Examples: - `SuffixArray("banana").lcp_of_ranks(1..3) == 3` - `SuffixArray("banana").lcp_of_ranks(3..4) == 6` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L1274) ### `SuffixArray.split` ```cp fn split(self, r: Range) -> Int ``` Where the rank range `r` splits in the suffix tree: the `k` in `r.start + 1..r.end` whose adjacent LCP `lcp[k - 1]` equals `lcp_of_ranks(r)`, so `r.start..k` and `k..r.end` are the first child and the rest. - **cost**: O(1) - **empty**: an `r` with fewer than two ranks traps - **ties**: the smallest such `k` - **traps**: when `r.len < 2` or `r` reaches outside `0..n` Examples: - `SuffixArray("banana").split(0..3) == 1` - `SuffixArray("banana").split(0..6) == 3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L1288) ### `SuffixArray.kth_distinct` ```cp fn kth_distinct(self, k: Int) -> ?Range ``` The `k`-th (0-based) lexicographically smallest distinct non-empty substring, as the positions `l..r` of one occurrence, or `None` when `k >= distinct()`. - **cost**: O(log n) - **ties**: the occurrence in the suffix of smallest rank that holds it - **order**: `k` counts in increasing lexicographic order; the range is increasing positions - **traps**: when `k < 0` Examples: - `SuffixArray("banana").kth_distinct(1) == Some(3..5)` - `SuffixArray("banana").kth_distinct(15) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L1301) ## `SuffixTreeEdge` ```cp pub struct SuffixTreeEdge( ``` O(1) value. One edge of the compressed suffix tree of a sequence, built in O(n) from SA + LCP. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L1321) ## `HashVal` ```cp pub struct HashVal(h1: Int, h2: Int) ``` O(1) space and comparison. A 64-bit double-mod polynomial hash value (`Copy + Eq + Ord + Hash`). Can itself be fed into another `RollingHash` (e.g. hashing rows into a column hash for 2D grids). [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L1429) ### `HashVal.hash_token` ```cp fn hash_token(self) -> Int ``` One integer that identifies the pair, `(h1 << 31) | h2`, so a `RollingHash` can hash a sequence of `HashVal` (rows of a grid, say). - **cost**: O(1) - **traps**: never Examples: - `HashVal(1, 2).hash_token == 2147483650` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L1436) ## `Hashable` ```cp pub trait Hashable ``` O(1) per element. Elements accepted by `RollingHash`: `Char`, `Int`, `Bool`, `HashVal`, or any user type implementing `hash_token`. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L1440) ### `Hashable.hash_token` ```cp fn hash_token(self) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L1441) ## `RollingHash` ```cp pub struct RollingHash ``` O(n) build, O(1) slice hash. Generalized double-mod polynomial rolling hash over `Str`, `List`, or any `[D]T` (`Char`, `Int`, `Bool`, `HashVal`). Built in O(n); substring queries `.get(l..r)` / `.slice(l, r)` and `.combine(a, b, b_len)` are O(1). Each constructor draws independent random salted bases unless `bases:` is passed explicitly, so 2D row and column hashes never collide on transposes. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L1451) ### `RollingHash.new` ```cp fn new(seq: S, bases: ?(Int, Int) = None) -> RollingHash ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L1459) ### `RollingHash.push` ```cp fn push(mut self, x: T) ``` Appends `x` to the end of the hashed sequence. - **cost**: O(1) amortized - **traps**: never Examples: - `var h = RollingHash("ab"); h.push('a'); h.all == h.hash_of("aba")` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L1500) ### `RollingHash.pop` ```cp fn pop(mut self) ``` Removes the last element of the hashed sequence. - **cost**: O(1) - **traps**: when the hash is empty Examples: - `var h = RollingHash("abc"); h.pop(); h.all == h.hash_of("ab")` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L1516) ### `RollingHash.hash_of` ```cp fn hash_of(self, seq: S) -> HashVal ``` The hash `seq` would have under `self`'s bases, without building a `RollingHash` of it; compare it with any slice of `self`. - **cost**: O(|seq|) - **empty**: `HashVal(0, 0)` - **traps**: never Examples: - `let h = RollingHash("xab"); h.hash_of("ab") == h.get(1..3)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L1530) ### `RollingHash.concat` ```cp fn concat(self, parts: List<(hash: HashVal, len: Int)>) -> HashVal ``` The hash of the concatenation of `parts`, each given as its hash and length, under `self`'s bases; `combine` folded left to right. - **cost**: O(|parts|) amortized - **empty**: `HashVal(0, 0)` - **traps**: when a `len` is negative Examples: - `let h = RollingHash("abcd"); h.concat([(h.get(0..2), 2), (h.get(2..4), 2)]) == h.all` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L1548) ### `RollingHash.len` ```cp fn len(self) -> Int ``` The number of elements hashed. - **cost**: O(1) - **traps**: never Examples: - `RollingHash("abc").len == 3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L1558) ### `RollingHash.is_empty` ```cp fn is_empty(self) -> Bool ``` True when no elements are hashed. - **cost**: O(1) - **traps**: never Examples: - `RollingHash("").is_empty == true` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L1565) ### `RollingHash.all` ```cp fn all(self) -> HashVal ``` The hash of the whole sequence, `self.get(0..self.len)`. - **cost**: O(1) - **traps**: never Examples: - `let h = RollingHash("abc"); h.all == h.get(0..3)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L1572) ### `RollingHash.raw_slice` ```cp fn raw_slice(self, l: Int, r: Int) -> HashVal ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L1575) ### `RollingHash.eq_sub` ```cp fn eq_sub(self, a: Int, b: Int, len: Int) -> Bool ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L1585) ### `RollingHash.slice` ```cp fn slice(self, l: Int, r: Int) -> HashVal ``` The hash of the half-open slice `l..r` (0-based); `HashVal(0, 0)` when `l == r`. - **cost**: O(1) - **traps**: when `l > r`, `l < 0` or `r > self.len` Examples: - `let h = RollingHash("abab"); h.slice(0, 2) == h.slice(2, 4) and h.slice(1, 1) == HashVal(0, 0)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L1597) ### `RollingHash.get` ```cp fn get(self, r: R) -> HashVal ``` The hash of a range of positions: `l..r`, `l..=r`, `..k`, `k..`, or a `Range` when the hash was built over a `[D]T`. The same value as `slice`. - **cost**: O(1) - **traps**: when the range reaches outside the hashed sequence Examples: - `let h = RollingHash("abab"); h.get(0..2) == h.get(2..=3)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L1608) ### `RollingHash.combine` ```cp fn combine(self, a: HashVal, b: HashVal, b_len: Int) -> HashVal ``` The hash of `a`'s sequence followed by `b`'s, where `b` has length `b_len`: `a * base^b_len + b` per modulus. - **cost**: O(1) amortized (the power table grows past `len` on demand) - **traps**: when `b_len < 0` Examples: - `let h = RollingHash("abc"); h.combine(h.get(0..1), h.get(1..3), 2) == h.all` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L1618) ### `RollingHash.lcp` ```cp fn lcp(self, a: Int, b: Int) -> Int ``` The length of the longest common prefix of the suffixes starting at `a` and `b`, by binary search on hashes (so it can be wrong on a collision). - **cost**: O(log n) - **traps**: when `a` or `b` is outside `0..=self.len` Examples: - `RollingHash("abcabd").lcp(0, 3) == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L1630) ### `RollingHash.lcs` ```cp fn lcs(self, a: Int, b: Int) -> Int ``` The length of the longest common suffix of the prefixes `s[..a]` and `s[..b]`, by binary search on hashes. - **cost**: O(log n) - **traps**: when `a` or `b` is outside `0..=self.len` Examples: - `RollingHash("xabyab").lcs(3, 6) == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L1647) ### `RollingHash.lcp_with` ```cp fn lcp_with(self, a: Int, other: RollingHash, b: Int) -> Int ``` The length of the longest common prefix of `self[a..]` and `other[b..]`, by binary search on hashes. Both hashes must use the same bases. - **cost**: O(log min(|self| - a, |other| - b)) - **traps**: when the bases differ, `a` is outside `0..=self.len` or `b` outside `0..=other.len` Examples: - `RollingHash("abcd", bases: Some((131, 137))).lcp_with(1, RollingHash("xbcx", bases: Some((131, 137))), 1) == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L1664) ## `Hash2D` ```cp pub struct Hash2D(bases: (Int, Int)) ``` O(R * C) build, O(1) rectangle hash. Double-mod 2D polynomial prefix hash over a grid with row domain `R` and column domain `C`. Built in O(R * C); `rect(rows, cols)` is O(1) and returns a `HashVal`. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L1678) ### `Hash2D.new` ```cp fn new(code: (R, C) -> Int, bases: ?(Int, Int) = None) -> Hash2D ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L1688) ### `Hash2D.rect` ```cp fn rect(self, rows: Range, cols: Range) -> HashVal ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L1740) ## `Hash61` ```cp pub struct Hash61(v ``` O(1) value. Single-modulus `2^61 - 1` (Mersenne prime) polynomial hash value (`Copy + Eq + Ord + Hash`). [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L1788) ## `RollingHash61` ```cp pub struct RollingHash61 ``` O(n) build, O(1) query. Single-modulus `2^61 - 1` polynomial rolling hash with randomized base. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L1791) ### `RollingHash61.new` ```cp fn new(seq: S, base: ?U64 = None) -> RollingHash61 ``` A single-modulus polynomial rolling hash of `seq` modulo the Mersenne prime `2^61 - 1`; call it as `RollingHash61(seq)`. Same scheme as `RollingHash` with one modulus: each token enters as `token % M + 1`; the base is drawn at random unless `base:` gives it. - **cost**: O(n) - **empty**: an empty hash; `push` can grow it - **traps**: when a given base is outside `2..2^61 - 1` Examples: - `let h = RollingHash61("abab"); h.get(0..2) == h.get(2..4)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L1805) ### `RollingHash61.len` ```cp fn len(self) -> Int ``` The number of elements hashed. - **cost**: O(1) - **traps**: never Examples: - `RollingHash61("abc").len == 3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L1825) ### `RollingHash61.is_empty` ```cp fn is_empty(self) -> Bool ``` True when no elements are hashed. - **cost**: O(1) - **traps**: never Examples: - `RollingHash61("").is_empty == true` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L1832) ### `RollingHash61.slice61` ```cp fn slice61(self, l: Int, r: Int) -> Hash61 ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L1835) ### `RollingHash61.all` ```cp fn all(self) -> Hash61 ``` The hash of the whole sequence, `self.get(0..self.len)`. - **cost**: O(1) - **traps**: never Examples: - `let h = RollingHash61("abc"); h.all == h.get(0..3)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L1845) ### `RollingHash61.get` ```cp fn get(self, r: R) -> Hash61 ``` The hash of a range of positions (`l..r`, `l..=r`, `..k`, `k..`, or a `Range` when built over a `[D]T`); an empty range hashes to `Hash61(0)`. - **cost**: O(1) - **traps**: when the range reaches outside the hashed sequence Examples: - `let h = RollingHash61("abab"); h.get(0..2) == h.get(2..=3)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L1853) ### `RollingHash61.combine` ```cp fn combine(self, a: Hash61, b: Hash61, b_len: Int) -> Hash61 ``` The hash of `a`'s sequence followed by `b`'s, where `b` has length `b_len`: `a * base^b_len + b` modulo `2^61 - 1`. - **cost**: O(1) amortized (the power table grows past `len` on demand) - **traps**: when `b_len < 0` Examples: - `let h = RollingHash61("abc"); h.combine(h.get(0..1), h.get(1..3), 2) == h.all` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L1864) ### `RollingHash61.push` ```cp fn push(mut self, x: T) ``` Appends `x` to the end of the hashed sequence. - **cost**: O(1) amortized - **traps**: never Examples: - `var h = RollingHash61("ab"); h.push('a'); h.push('b'); h.get(0..2) == h.get(2..4)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L1882) ### `RollingHash61.pop` ```cp fn pop(mut self) ``` Removes the last element of the hashed sequence. - **cost**: O(1) - **traps**: when the hash is empty Examples: - `var h = RollingHash61("abab"); h.pop(); h.len == 3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L1893) ### `RollingHash61.lcp` ```cp fn lcp(self, a: Int, b: Int) -> Int ``` The length of the longest common prefix of the suffixes starting at `a` and `b`, by binary search on hashes. - **cost**: O(log n) - **traps**: when `a` or `b` is outside `0..=self.len` Examples: - `RollingHash61("abcabd").lcp(0, 3) == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L1903) ### `RollingHash61.lcs` ```cp fn lcs(self, a: Int, b: Int) -> Int ``` The length of the longest common suffix of the prefixes `s[..a]` and `s[..b]`, by binary search on hashes. - **cost**: O(log n) - **traps**: when `a` or `b` is outside `0..=self.len` Examples: - `RollingHash61("xabyab").lcs(3, 6) == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L1919) ### `RollingHash61.lcp_with` ```cp fn lcp_with(self, a: Int, other: RollingHash61, b: Int) -> Int ``` The length of the longest common prefix of `self[a..]` and `other[b..]`, by binary search on hashes. Both hashes must use the same base. - **cost**: O(log min(|self| - a, |other| - b)) - **traps**: when the bases differ, `a` is outside `0..=self.len` or `b` outside `0..=other.len` Examples: - `RollingHash61("abcd", base: Some(U64(131))).lcp_with(1, RollingHash61("xbcx", base: Some(U64(131))), 1) == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L1935) ## `DynamicHash` ```cp pub struct DynamicHash ``` O(n) build, O(log n) point update and range hash. Mutable double-mod rolling hash over domain `D`. Supports `h[i] = x` via W8 `IndexSet`. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L1949) ### `DynamicHash.new` ```cp fn new(seq: S, bases: ?(Int, Int) = None) -> DynamicHash ``` A double-modulus rolling hash of `seq` that supports point updates, kept forwards and backwards in a segment tree; call it as `DynamicHash(seq)`. Positions are `seq`'s keys (domain `D`); hashes follow the `RollingHash` scheme and bases. - **cost**: O(n) - **empty**: an empty hash - **traps**: when a given base is outside `2..M` Examples: - `let h = DynamicHash("abab"); h.get(0..2) == h.get(2..4)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L1960) ### `DynamicHash.len` ```cp fn len(self) -> Int ``` The number of hashed positions, `D.K`. - **cost**: O(1) - **traps**: never Examples: - `DynamicHash("abc").len == 3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L1967) ### `DynamicHash.is_empty` ```cp fn is_empty(self) -> Bool ``` True when there are no positions. - **cost**: O(1) - **traps**: never Examples: - `DynamicHash("").is_empty == true` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L1974) ### `DynamicHash.all` ```cp fn all(self) -> HashVal ``` The hash of the whole sequence, `self.get(..)`. - **cost**: O(1) - **traps**: never Examples: - `let h = DynamicHash("abab"); h.all == h.get(0..4)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L1981) ### `DynamicHash.set` ```cp fn set(mut self, i: D, x: T) ``` Replaces the element at position `i` with `x`; `h[i] = x` means the same. - **cost**: O(log n) - **traps**: never (`i` is a `D`) Examples: - `var h = DynamicHash("abxb"); h.set(2, 'a'); h.get(0..2) == h.get(2..4)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L1988) ### `DynamicHash.get` ```cp fn get(self, r: Range) -> HashVal ``` The hash of the elements over `r` in order (a cut range `j..i` works too, decision 124). - **cost**: O(log n) - **empty**: an empty `r` gives `HashVal(0, 0)` - **traps**: never (`r` is a `Range`) Examples: - `let h = DynamicHash("xyxy"); h.get(0..2) == h.get(2..4)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L1996) ### `DynamicHash.rev_get` ```cp fn rev_get(self, r: Range) -> HashVal ``` The hash of the elements over `r` read backwards, comparable with `get`. - **cost**: O(log n) - **empty**: an empty `r` gives `HashVal(0, 0)` - **traps**: never (`r` is a `Range`) Examples: - `let h = DynamicHash("abba"); h.rev_get(0..2) == h.get(2..4)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2004) ### `DynamicHash.is_palindrome` ```cp fn is_palindrome(self, r: Range) -> Bool ``` True when the elements over `r` read the same both ways: `get(r) == rev_get(r)`. - **cost**: O(log n) - **empty**: `true` for an empty `r` - **traps**: never (`r` is a `Range`) Examples: - `let h = DynamicHash("abca"); h.is_palindrome(1..2) and not h.is_palindrome(0..4)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2012) ## `SuffixAutomaton` ```cp pub struct SuffixAutomaton ``` O(n * |A|) space, O(1) amortized push. Online suffix automaton over alphabet domain `A`. O(n * |A|) flat memory, O(n) amortized build, O(states) `topo_order` and `occurrences`. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2018) ### `SuffixAutomaton.new` ```cp fn new() -> SuffixAutomaton ``` An empty suffix automaton over the alphabet domain `A`: only the root state `0`. Call it as `SuffixAutomaton()`, then `push` letters. - **cost**: O(|A|) - **traps**: never Examples: - `SuffixAutomaton().len == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2034) ### `SuffixAutomaton.of` ```cp fn of(s: S) -> SuffixAutomaton ``` The suffix automaton of `s`: `SuffixAutomaton()` followed by `push` of each element. States are numbered in creation order: each `push` creates its new state, then the clone if one is needed. For `"abb"` the states are `0` (empty), `1` (`a`), `2` (`ab`), `3` (`abb`, `bb`) and `4` (`b`, the clone). - **cost**: O(|s| * |A|) memory, O(|s|) amortized time - **empty**: only the root - **traps**: when an element of `s` is not in `A` Examples: - `SuffixAutomaton.of("abb").len == 5` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2050) ### `SuffixAutomaton.add_empty_state` ```cp fn add_empty_state(mut self, length: Int, is_prefix: Bool) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2056) ### `SuffixAutomaton.clone_state` ```cp fn clone_state(mut self, src: Int, length: Int) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2066) ### `SuffixAutomaton.push` ```cp fn push(mut self, a: A) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2077) ### `SuffixAutomaton.root` ```cp fn root(self) -> Int ``` The root state, for the empty string: always `0`. - **cost**: O(1) - **traps**: never Examples: - `SuffixAutomaton.of("ab").root == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2111) ### `SuffixAutomaton.len` ```cp fn len(self) -> Int ``` The number of states, the root included; at most `max(1, 2n - 1)`. - **cost**: O(1) - **traps**: never Examples: - `SuffixAutomaton.of("abb").len == 5` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2118) ### `SuffixAutomaton.step` ```cp fn step(self, state: Int, a: A) -> ?Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2121) ### `SuffixAutomaton.link` ```cp fn link(self, state: Int) -> ?Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2132) ### `SuffixAutomaton.longest` ```cp fn longest(self, state: Int) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2143) ### `SuffixAutomaton.shortest` ```cp fn shortest( self, state: Int, ) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2151) ### `SuffixAutomaton.first_pos` ```cp fn first_pos(self, state: Int) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2162) ### `SuffixAutomaton.find` ```cp fn find(self, word: S) -> ?Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2172) ### `SuffixAutomaton.contains` ```cp fn contains(self, word: S) -> Bool ``` True when `word` is a substring of the automaton's string: `find(word) != None`. - **cost**: O(|word|) - **empty**: `true` for an empty `word` - **traps**: when an element of `word` is not in `A` Examples: - `let m = SuffixAutomaton.of("abb"); m.contains("ab") and not m.contains("ba")` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2194) ### `SuffixAutomaton.distinct` ```cp fn distinct(self) -> Int ``` The number of distinct non-empty substrings: the sum of `longest(v) - shortest(v) + 1` over the states other than the root. - **cost**: O(states) - **traps**: never Examples: - `SuffixAutomaton.of("abb").distinct() == 5` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2202) ### `SuffixAutomaton.topo_order` ```cp fn topo_order(self) -> List ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2209) ### `SuffixAutomaton.occ_counts` ```cp fn occ_counts(self) -> List ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2232) ### `SuffixAutomaton.lcs` ```cp fn lcs(self, other: S) -> (len: Int, end: Int) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2250) ### `SuffixAutomaton.reset` ```cp fn reset(mut self) ``` Moves the append point back to the root, so the next `push` starts a new word of a generalized automaton (the substrings of all words added so far). - **cost**: O(1) - **traps**: never Examples: - `var m = SuffixAutomaton.of("ab"); m.reset(); m.push('c'); m.contains("c") and not m.contains("bc")` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2281) ### `SuffixAutomaton.add_word` ```cp fn add_word(mut self, word: S) ``` Adds `word` as a separate word of a generalized automaton: `reset()`, then `push` each letter. Afterwards the automaton holds the substrings of every word added. - **cost**: O(|word|) amortized - **empty**: an empty `word` only resets - **traps**: when an element of `word` is not in `A` Examples: - `var m = SuffixAutomaton(); m.add_word("ab"); m.add_word("b"); m.distinct() == 3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2291) ### `SuffixAutomaton.states` ```cp fn states(self) -> yields Int ``` Every state in the order of `topo_order`, lazily. - **cost**: O(states) - **order**: non-decreasing `longest`; ties by smaller state number - **traps**: never Examples: - `SuffixAutomaton.of("abb").states().collect() == [0, 1, 4, 2, 3]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2301) ### `SuffixAutomaton.endpos_tree` ```cp fn endpos_tree(self) -> List> ``` The suffix-link tree as child lists: entry `v` lists the states whose link is `v`. Rooted at `0`. - **cost**: O(states) - **order**: keyed by state; each child list in increasing state number - **traps**: never Examples: - `SuffixAutomaton.of("abb").endpos_tree() == [[1, 4], [], [], [], [2, 3]]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2311) ### `SuffixAutomaton.kth_substring` ```cp fn kth_substring(self, k: Int, distinct: Bool = true) -> ?List ``` The `k`-th (0-based) non-empty substring in lexicographic order, as its letters, or `None` when there are not that many. With `distinct: false` each substring counts once per occurrence. A proper prefix comes before its extensions. - **cost**: O(states * |A|) - **ties**: with `distinct: false`, copies of one substring are adjacent and interchangeable - **order**: the letters of the substring, first to last - **traps**: when `k < 0` Examples: - `SuffixAutomaton.of("abb").kth_substring(3) == Some(['b'])` - `SuffixAutomaton.of("abb").kth_substring(5, distinct: false) == Some(['b', 'b'])` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2328) ## `PalindromicTree` ```cp pub struct PalindromicTree ``` O(n * |A|) space, O(1) amortized push. Online palindromic tree (eertree) over alphabet domain `A`, with `diff` and `series_link` for O(n log n) palindromic partition DP. State `0` is the odd root (`pal_len == -1`); state `1` is the even root (`pal_len == 0`). [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2408) ### `PalindromicTree.new` ```cp fn new() -> PalindromicTree ``` An empty palindromic tree over the alphabet domain `A`: just the odd root `0` and the even root `1`. Call it as `PalindromicTree()`. - **cost**: O(|A|) - **traps**: never Examples: - `PalindromicTree().len == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2428) ### `PalindromicTree.of` ```cp fn of(s: S) -> PalindromicTree ``` The palindromic tree of `s`: `PalindromicTree()` followed by `push` of each element. New states are numbered from `2` in creation order. - **cost**: O(|s| * |A|) memory, O(|s|) amortized time - **empty**: just the two roots - **traps**: when an element of `s` is not in `A` Examples: - `PalindromicTree.of("aba").distinct == 3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2439) ### `PalindromicTree.push` ```cp fn push(mut self, a: A) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2445) ### `PalindromicTree.size` ```cp fn size(self) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2480) ### `PalindromicTree.at` ```cp fn at(self, i: Int) -> A ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2483) ### `PalindromicTree.grow` ```cp fn grow(mut self, cur: Int, c: Int, link_to: Int) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2486) ### `PalindromicTree.len` ```cp fn len(self) -> Int ``` The number of states, both roots included: `distinct + 2`. - **cost**: O(1) - **traps**: never Examples: - `PalindromicTree.of("aba").len == 5` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2505) ### `PalindromicTree.distinct` ```cp fn distinct(self) -> Int ``` The number of distinct non-empty palindromic substrings, `len - 2`; at most `n`. - **cost**: O(1) - **traps**: never Examples: - `PalindromicTree.of("aba").distinct == 3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2512) ### `PalindromicTree.pal_len` ```cp fn pal_len(self, state: Int) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2515) ### `PalindromicTree.link` ```cp fn link(self, state: Int) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2523) ### `PalindromicTree.step` ```cp fn step(self, state: Int, a: A) -> ?Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2532) ### `PalindromicTree.diff` ```cp fn diff(self, state: Int) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2543) ### `PalindromicTree.series_link` ```cp fn series_link(self, state: Int) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2552) ### `PalindromicTree.occ_counts` ```cp fn occ_counts(self) -> List ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2563) ### `PalindromicTree.push_front` ```cp fn push_front(mut self, a: A) -> Int ``` Prepends the letter `a` (a double-ended tree) and returns the state of the longest palindromic prefix of the new string, creating it if it is new. - **cost**: O(1) amortized - **traps**: never (`a` is an `A`) Examples: - `var t = PalindromicTree.of("ba"); t.push_front('a') == 4` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2583) ### `PalindromicTree.pop` ```cp fn pop(mut self) ``` Undoes the most recent `push` not yet undone, removing the state it created if any, so a DFS over a tree of strings can back out. - **cost**: O(1) amortized - **traps**: when there is no `push` to undo Examples: - `var t = PalindromicTree.of("ab"); t.pop(); t.distinct == 1 and t.last_state == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2615) ### `PalindromicTree.last_state` ```cp fn last_state(self) -> Int ``` The state of the longest palindromic suffix of the current string; the even root `1` when the string is empty. - **cost**: O(1) - **ties**: None; the longest suffix is unique - **traps**: never Examples: - `PalindromicTree.of("aba").last_state == 4` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2640) ### `PalindromicTree.contains` ```cp fn contains(self, word: S) -> Bool ``` True when `word` is a palindrome occurring in the pushed string, that is, a state of the tree. - **cost**: O(|word|) - **empty**: `true` (the even root) - **traps**: never Examples: - `let t = PalindromicTree.of("aba"); t.contains("aba") and not t.contains("ab")` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2649) ### `PalindromicTree.min_palindrome_partition` ```cp fn min_palindrome_partition(self) -> List ``` `dp[i]` is the least number of palindromes the first `i` pushed letters split into, for `i in 0..=n`, by the series-link DP. - **cost**: O(n log n) - **ties**: None; only the count is returned - **order**: keyed by prefix length `0..=n` - **traps**: never Examples: - `PalindromicTree.of("aab").min_palindrome_partition() == [0, 1, 1, 2]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2674) ## `Trie` ```cp pub struct Trie ``` Dynamic trie over alphabet domain `A`. O(|word|) per operation; flat `|A|`-stride table. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2691) ### `Trie.new` ```cp fn new() -> Trie ``` An empty trie over the alphabet domain `A`: one root node `0`, no words. Call it as `Trie()`. Nodes are numbered in creation order. - **cost**: O(|A|) - **traps**: never Examples: - `Trie().len == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2703) ### `Trie.root` ```cp fn root(self) -> Int ``` The root node, for the empty word: always `0`. - **cost**: O(1) - **traps**: never Examples: - `Trie().root == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2712) ### `Trie.len` ```cp fn len(self) -> Int ``` The number of nodes, the root included. `remove` keeps nodes, so this never shrinks except by `clear`. - **cost**: O(1) - **traps**: never Examples: - `var t = Trie(); t.add("ab"); t.add("ac"); t.len == 4` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2720) ### `Trie.is_empty` ```cp fn is_empty(self) -> Bool ``` True when no words are stored (every count is zero), whatever nodes remain. - **cost**: O(1) - **traps**: never Examples: - `var t = Trie(); t.add("a"); t.remove("a"); t.is_empty` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2727) ### `Trie.step` ```cp fn step(self, node: Int, a: A) -> ?Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2730) ### `Trie.find` ```cp fn find(self, word: S) -> ?Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2740) ### `Trie.add` ```cp fn add(mut self, word: S) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2757) ### `Trie.remove` ```cp fn remove(mut self, word: S) -> Bool ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2781) ### `Trie.count` ```cp fn count(self, word: S) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2800) ### `Trie.count_prefix` ```cp fn count_prefix(self, prefix: S) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2811) ### `Trie.ends_at` ```cp fn ends_at(self, node: Int) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2822) ### `Trie.pass_at` ```cp fn pass_at(self, node: Int) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2830) ### `Trie.contains` ```cp fn contains(self, word: S) -> Bool ``` True when at least one copy of exactly `word` is stored: `count(word) > 0`. - **cost**: O(|word|) - **empty**: whether the empty word is stored - **traps**: never Examples: - `var t = Trie(); t.add("ab"); t.contains("ab") and not t.contains("a")` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2843) ### `Trie.clear` ```cp fn clear(mut self) ``` Removes every word and node, leaving just the root. - **cost**: O(1) - **traps**: never Examples: - `var t = Trie(); t.add("ab"); t.clear(); t.is_empty and t.len == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2851) ### `Trie.kth` ```cp fn kth(self, k: Int) -> ?List ``` The `k`-th (0-based) stored word in lexicographic order, copies counted, as its letters; `None` when fewer than `k + 1` words are stored. A word comes before its extensions. - **cost**: O(depth * |A|) - **ties**: copies of one word are adjacent and interchangeable - **order**: the letters of the word, first to last - **traps**: when `k < 0` Examples: - `var t = Trie(); t.add("b"); t.add("ab"); t.add("a"); t.kth(1) == Some(['a', 'b']) and t.kth(3) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2865) ### `Trie.count_less` ```cp fn count_less(self, word: S) -> Int ``` The number of stored words (with multiplicity) lexicographically smaller than `word`. - **cost**: O(|word| * |A|) - **empty**: `0` for an empty `word` - **traps**: never Examples: - `var t = Trie(); t.add("b"); t.add("ab"); t.add("a"); t.count_less("b") == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2873) ## `AhoCorasick` ```cp pub struct AhoCorasick ``` O(total * |A|) build, O(1) step. Aho-Corasick multi-pattern automaton over alphabet domain `A`. Built in O(sum |p| * |A|) flat memory and time; `step`, `link`, and `hit` are O(1). [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2889) ### `AhoCorasick.new` ```cp fn new(patterns: List) -> AhoCorasick ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2900) ### `AhoCorasick.root` ```cp fn root(self) -> Int ``` The root state, before any letter is read: always `0`. - **cost**: O(1) - **traps**: never Examples: - `AhoCorasick(["a"]).root == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2957) ### `AhoCorasick.len` ```cp fn len(self) -> Int ``` The number of states, the root included. - **cost**: O(1) - **traps**: never Examples: - `AhoCorasick(["a", "ab", "b"]).len == 4` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2964) ### `AhoCorasick.step` ```cp fn step(self, state: Int, a: A) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2967) ### `AhoCorasick.link` ```cp fn link(self, state: Int) -> Int ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2976) ### `AhoCorasick.hit` ```cp fn hit(self, state: Int) -> Bool ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2985) ### `AhoCorasick.words_at` ```cp fn words_at(self, state: Int) -> List ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L2994) ### `AhoCorasick.find_all` ```cp fn find_all(self, text: S) -> yields (at: Int, pattern: Int) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L3009) ### `AhoCorasick.counts` ```cp fn counts(self, text: S) -> List ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L3030) ### `AhoCorasick.fail_order` ```cp fn fail_order(self) -> List ``` Every state in BFS order of the trie (root first, then by depth, equal depths by state number), so each state comes after its failure link; iterate backwards for bottom-up DP. - **cost**: O(states) - **order**: non-decreasing depth; ties by smaller state number - **traps**: never Examples: - `AhoCorasick(["a", "ab", "b"]).fail_order() == [0, 1, 3, 2]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L3057) ### `AhoCorasick.exit_link` ```cp fn exit_link(self, state: Int) -> ?Int ``` The nearest state strictly up the failure links of `state` at which a pattern ends, or `None` when there is None. - **cost**: O(1) - **traps**: when `state` is outside `0..self.len` Examples: - `let ac = AhoCorasick(["a", "ab", "b"]); ac.exit_link(2) == Some(3) and ac.exit_link(1) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L3065) ### `AhoCorasick.pattern_state` ```cp fn pattern_state(self, pattern: Int) -> Int ``` The state where `patterns[pattern]` ends. - **cost**: O(1) - **traps**: when `pattern` is outside `0..patterns.len` Examples: - `AhoCorasick(["a", "ab", "b"]).pattern_state(1) == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L3074) ## `DynamicAhoCorasick` ```cp pub struct DynamicAhoCorasick ``` O(|pat| * |A| * log n) amortized insert/delete, O(|text| * log n) query. Online multi-pattern Aho-Corasick via log-decomposed static buckets. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L3080) ### `DynamicAhoCorasick.new` ```cp fn new() -> DynamicAhoCorasick ``` An empty online pattern set over the alphabet domain `A`; call it as `DynamicAhoCorasick()`. - **cost**: O(1) - **traps**: never Examples: - `DynamicAhoCorasick().is_empty` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L3089) ### `DynamicAhoCorasick.len` ```cp fn len(self) -> Int ``` The number of patterns stored, copies counted. - **cost**: O(1) - **traps**: never Examples: - `var d = DynamicAhoCorasick(); d.add("a"); d.add("a"); d.len == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L3096) ### `DynamicAhoCorasick.is_empty` ```cp fn is_empty(self) -> Bool ``` True when no patterns are stored. - **cost**: O(1) - **traps**: never Examples: - `var d = DynamicAhoCorasick(); d.add("a"); d.remove("a"); d.is_empty` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L3103) ### `DynamicAhoCorasick.add` ```cp fn add(mut self, pattern: S) ``` Stores one more copy of `pattern`. - **cost**: O(|pattern| * |A| * log n) amortized - **empty**: an empty pattern matches at every `at` in `0..=|text|` - **traps**: when an element of `pattern` is not in `A` Examples: - `var d = DynamicAhoCorasick(); d.add("ab"); d.len == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L3111) ### `DynamicAhoCorasick.remove` ```cp fn remove(mut self, pattern: S) ``` Removes one stored copy of `pattern`. - **cost**: O(|pattern| * |A| * log n) amortized - **empty**: removes a copy of the empty pattern - **traps**: when no copy of `pattern` is stored Examples: - `var d = DynamicAhoCorasick(); d.add("ab"); d.remove("ab"); d.count_matches("ab") == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L3119) ### `DynamicAhoCorasick.count_matches` ```cp fn count_matches(self, text: S) -> Int ``` The total number of occurrences of all stored patterns in `text`, overlaps and copies counted. - **cost**: O(|text| * log n) - **empty**: `0` for an empty `text` unless an empty pattern is stored - **traps**: when an element of `text` is not in `A` Examples: - `var d = DynamicAhoCorasick(); d.add("ab"); d.add("b"); d.count_matches("abb") == 3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/strings.cp#L3128) --- # subset URL: /docs/ref/std/subset Generated from [spec/std/subset.cp](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/subset.cp) by `cpl doc --format json`. ## `Subset` ```cp pub struct Subset(bits: U64) ``` A subset of a domain `B` of at most 64 members, stored as one word (bit `k` for `B`'s `k`-th position). `B.subsets` is the domain of all `2^|B|` of them, so `[B.subsets]T` is a mask-DP table, and `{}` is the empty subset. Every operation here is O(1) unless it says otherwise. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/subset.cp#L6) ### `Subset.empty` ```cp fn empty() -> Subset ``` The empty subset, also written `{}`. - **cost**: O(1) - **traps**: never Examples: - `domain B = 0..4; Subset.empty.len == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/subset.cp#L12) ### `Subset.full` ```cp fn full() -> Subset ``` Every member of `B`: the word with its low `|B|` bits set. - **cost**: O(1) - **traps**: never Examples: - `domain B = 0..4; Subset.full.len == 4` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/subset.cp#L19) ### `Subset.single` ```cp fn single(b: B) -> Subset ``` `{b}`: the subset whose only member is `b`. - **cost**: O(1) - **traps**: never Examples: - `domain B = 0..4; Subset.single(B(2)).items.collect() == [B(2)]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/subset.cp#L28) ### `Subset.contains` ```cp fn contains(self, b: B) -> Bool ``` Whether `b` is a member; `b in s` calls it and `b not in s` negates it. - **cost**: O(1) - **traps**: never Examples: - `domain B = 0..4; let s = Subset.single(B(1)); B(1) in s and B(2) not in s` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/subset.cp#L35) ### `Subset.len` ```cp fn len(self) -> Int ``` The number of members (a popcount). - **cost**: O(1) - **traps**: never Examples: - `domain B = 0..4; Subset.single(B(0)).with(B(3)).len == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/subset.cp#L42) ### `Subset.with` ```cp fn with(self, b: B) -> Subset ``` `self` with `b` added. Adding a member already present returns `self` unchanged. - **cost**: O(1) - **traps**: never Examples: - `domain B = 0..4; Subset.empty.with(B(1)).with(B(1)) == Subset.single(B(1))` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/subset.cp#L49) ### `Subset.without` ```cp fn without(self, b: B) -> Subset ``` `self` with `b` removed. Removing a non-member returns `self` unchanged. - **cost**: O(1) - **traps**: never Examples: - `domain B = 0..4; Subset.full.without(B(0)).len == 3` - `domain B = 0..4; Subset.empty.without(B(2)) == Subset.empty` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/subset.cp#L57) ### `Subset.set` ```cp fn set(mut self, b: B, on: Bool) ``` Add `b` when `on`, remove it otherwise, in place (as `Bitset.set`). - **cost**: O(1) - **traps**: never Examples: - `domain B = 0..4; var s = Subset.empty; s.set(B(2), true); s.set(B(0), false); s == Subset.single(B(2))` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/subset.cp#L64) ### `Subset.shifted` ```cp fn shifted(self, k: Int) -> Subset ``` A new set with every member `k` places up (down for a negative `k`); members that leave `B` are dropped (as `Bitset.shifted`). - **cost**: O(1) - **traps**: never Examples: - `domain B = 0..4; Subset.single(B(1)).with(B(3)).shifted(1) == Subset.single(B(2))` - `domain B = 0..4; Subset.single(B(1)).shifted(-2) == Subset.empty` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/subset.cp#L74) ### `Subset.complement` ```cp fn complement(self) -> Subset ``` The members of `B` not in `self`; no bit at or above `|B|` is ever set. - **cost**: O(1) - **traps**: never Examples: - `domain B = 0..4; Subset.single(B(0)).complement().len == 3` - `domain B = 0..4; Subset.empty.complement() == Subset.full` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/subset.cp#L85) ### `Subset.first` ```cp fn first(self) -> ?B ``` The least member in `B`'s order (the lowest set bit, by count-trailing-zeros), `None` for `{}`. Peels one member per step in a mask DP: `s.first()` then `s.without(b)`. - **cost**: O(1) - **empty**: `None` - **ties**: None possible; members are distinct, and the least in `B`'s order wins - **traps**: never Examples: - `domain B = 0..4; Subset.single(B(3)).with(B(1)).first() == Some(B(1))` - `domain B = 0..4; Subset.empty.first() == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/subset.cp#L96) ### `Subset.items` ```cp fn items(self) -> yields B ``` The members in `B`'s order; `for b in s` walks the same sequence. - **cost**: O(1) per member - **empty**: yields nothing - **order**: increasing in `B`'s order (increasing bit index) - **traps**: never Examples: - `domain B = 0..4; Subset.single(B(3)).with(B(1)).items.collect() == [B(1), B(3)]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/subset.cp#L107) ### `Subset.subsets` ```cp fn subsets(self) -> yields Subset ``` Every subset of `self`, `self` first and `{}` last: the submask walk `g = (g - 1) & self`, so the masks come in decreasing order as words. `2^s.len` subsets. - **cost**: O(1) per subset, `2^s.len` subsets - **empty**: `{}.subsets` yields `{}` once - **order**: decreasing as words: `self` first, `{}` last - **traps**: never Examples: - `domain B = 0..3; let s = Subset.single(B(0)).with(B(1)); s.subsets.map(g => g.first()).collect() == [Some(B(0)), Some(B(1)), Some(B(0)), None]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/subset.cp#L121) ### `Subset.supersets` ```cp fn supersets(self) -> yields Subset ``` Every superset of `self` within `B`, `self` first and `B` last: the walk `g = (g + 1) | self`, so the masks come in increasing order as words. `2^(|B| - s.len)` supersets. - **cost**: O(1) per superset, `2^(|B| - s.len)` supersets - **empty**: `{}.supersets` yields every subset of `B`, `{}` first - **order**: increasing as words: `self` first, `Subset.full` last - **traps**: never Examples: - `domain B = 0..3; Subset.single(B(1)).supersets.map(g => g.len).collect() == [1, 2, 2, 3]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/subset.cp#L137) ## `Subset` ```cp impl BitOr for Subset ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/subset.cp#L145) ### `Subset.bitor` ```cp fn bitor(a, b) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/subset.cp#L146) ## `Subset` ```cp impl BitAnd for Subset ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/subset.cp#L148) ### `Subset.bitand` ```cp fn bitand(a, b) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/subset.cp#L149) ## `Subset` ```cp impl BitXor for Subset ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/subset.cp#L151) ### `Subset.bitxor` ```cp fn bitxor(a, b) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/subset.cp#L152) ## `Subset` ```cp impl Sub for Subset ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/subset.cp#L154) ### `Subset.sub` ```cp fn sub(a, b) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/subset.cp#L155) --- # timetree URL: /docs/ref/std/timetree Generated from [spec/std/timetree.cp](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/timetree.cp) by `cpl doc --format json`. ## `TimeStep` ```cp pub enum TimeStep ``` One step in a `TimeTree` DFS traversal: - `Apply(id)`: apply event `tt.event(id)` on entry to a segment-tree node. - `Query(t)`: answer time slot `t` at a leaf. - `Undo`: revert the most recently applied event in LIFO order on exit. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/timetree.cp#L12) ### `TimeStep.Apply` ```cp Apply(id: Int) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/timetree.cp#L13) ### `TimeStep.Query` ```cp Query(t: Int) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/timetree.cp#L14) ### `TimeStep.Undo` ```cp Undo ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/timetree.cp#L15) ## `TimeTree` ```cp pub struct TimeTree ``` Offline segment tree over time `[0, q)` holding events of type `E` active on half-open intervals `[lo, hi)`. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/timetree.cp#L19) ### `TimeTree.new` ```cp fn new(q: Int) -> TimeTree ``` An empty timeline of `q` time slots `0..q`, with no events scheduled yet. - **cost**: O(q) time and memory - **traps**: when `q < 0` Examples: - `TimeTree(2).steps().len == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/timetree.cp#L31) ### `TimeTree.link` ```cp fn link(mut self, u: Int, ev: E) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/timetree.cp#L36) ### `TimeTree.add_interval` ```cp fn add_interval(mut self, lo: Int, hi: Int, ev: E) ``` Schedule `ev` to be active at every time slot in `lo..hi` (half-open). The interval is stored on the O(log q) segment-tree nodes that cover it, one copy of `ev` on each. An empty interval (`lo >= hi`) schedules nothing. - **cost**: O(log q) - **traps**: when `lo < 0` or `hi > q` on a non-empty interval Examples: - `var tt = TimeTree(2); tt.add_interval(0, 2, "e"); tt.steps().len == 4` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/timetree.cp#L50) ### `TimeTree.event` ```cp fn event(self, id: Int) -> E ``` The event carried by `TimeStep.Apply(id)`. Ids are `0, 1, 2, ...` in the order the node copies were stored by `add_interval` / `add_range`; read them from the steps, never compute them. - **cost**: O(1) - **traps**: when `id` is not an id that some `Apply` step carries Examples: - `var tt = TimeTree(2); tt.add_interval(0, 2, "e"); tt.event(0) == "e"` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/timetree.cp#L72) ### `TimeTree.emit_dfs` ```cp fn emit_dfs(self, u: Int, nl: Int, nr: Int, mut out: List) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/timetree.cp#L74) ### `TimeTree.steps` ```cp fn steps(self) -> List ``` The whole depth-first walk over `0..q` as a list. Entering a node emits one `Apply(id)` per event stored there, in scheduling order; a leaf `t` then emits `Query(t)`; leaving the node emits one `Undo` per `Apply` it emitted, so undos match applies in LIFO order. Children are visited left (earlier times) before right. see: `run`, which walks the same order without building the list - **cost**: O(q + m log q) time and memory for `m` scheduled intervals - **empty**: `[]` when `q == 0` - **order**: DFS order; `Query(t)` appears once per `t`, in increasing `t` - **traps**: never Examples: - `TimeTree(2).steps() == [TimeStep.Query(0), TimeStep.Query(1)]` - `var tt = TimeTree(2); tt.add_interval(0, 2, "e"); tt.steps() == [TimeStep.Apply(0), TimeStep.Query(0), TimeStep.Query(1), TimeStep.Undo]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/timetree.cp#L102) ### `TimeTree.run_node` ```cp fn run_node( self, u: Int, nl: Int, nr: Int, mark: () -> M, apply: E -> (), answer: Int -> R, undo: M -> (), mut out: List, ) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/timetree.cp#L108) ### `TimeTree.run` ```cp fn run( self, mark: () -> M, apply: E -> (), answer: Int -> R, undo: M -> (), ) -> List ``` Walk the same order as `steps` with callbacks instead of a list. On entering a node that holds at least one event it calls `mark()` once, then `apply(ev)` for each event there in scheduling order; at each leaf `t` it calls `answer(t)`; on leaving such a node it calls `undo(m)` once with the value its `mark()` returned. Nodes with no events call neither. - **cost**: O(q + m log q) callback calls for `m` scheduled intervals, O(log q) extra stack - **empty**: `[]` when `q == 0` - **order**: `[answer(0), ..., answer(q - 1)]`, indexed by time - **traps**: never (callbacks may trap) Examples: - `TimeTree(2).run(mark: () => 0, apply: e => (), answer: t => t * 10, undo: m => ()) == [0, 10]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/timetree.cp#L144) ### `TimeTree.add_range` ```cp fn add_range(mut self, r: Range, ev: E) ``` Schedule `ev` to be active at every time slot in `r`; `add_interval` with the range form. An empty `r` schedules nothing. - **cost**: O(log q) - **empty**: schedules nothing - **traps**: when a non-empty `r` reaches outside `0..q` Examples: - `var tt = TimeTree(3); tt.add_range(1..3, "e"); tt.steps().len == 7` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/timetree.cp#L163) ### `TimeTree.walk` ```cp fn walk(self) -> yields TimeStep ``` The steps of `steps`, yielded one at a time without building the list. - **cost**: O(1) amortized per step, O(log q) extra stack - **order**: the same DFS order as `steps` - **traps**: never Examples: - `TimeTree(2).walk().collect() == [TimeStep.Query(0), TimeStep.Query(1)]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/timetree.cp#L174) --- # tree URL: /docs/ref/std/tree Generated from [spec/std/tree.cp](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp) by `cpl doc --format json`. ## `Rooted` ```cp pub struct Rooted ``` A tree rooted at `root`, owning its own fresh heavy-first preorder domain `t.Pre`. Built in O(n) without recursion; memory is seven `[V]` arrays, one `[Pre]` array and child lists. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L25) ### `Rooted.par` ```cp par: [V]?V ``` The parent; `None` at the root. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L28) ### `Rooted.far` ```cp far: [V]Int ``` The total edge length from the root; equal to the depth when the edges have no lengths. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L31) ### `Rooted.sz` ```cp sz: [V]1..=V.count ``` The number of vertices in the subtree. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L33) ### `Rooted.bfs` ```cp bfs: List ``` Breadth-first order: the children of `v` are `bfs[k0[v]..k1[v]]`, so no vertex owns a list. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L35) ### `Rooted.heavy` ```cp heavy: [V]?V ``` The child with the largest subtree; `None` at a leaf. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L39) ### `Rooted.top` ```cp top: [V]V ``` The highest vertex of the heavy chain through `v`. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L41) ### `Rooted.at` ```cp at: [Pre]V ``` The inverse of `tin` / `pos`. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L44) ### `Rooted.new` ```cp fn new(next: Next, root: V) -> Rooted ``` Roots the tree given by `next` at `root`: `Rooted(g, root: r)` for a `Graph`, `Rooted(lists, root: r)` for a table of neighbour lists `[V]List`, and `Rooted(root: r, next: u => ...)` for anything else. `next` may list every neighbour (the parent is skipped) or only the children, as vertices or as arcs. The tree is the breadth-first spanning tree from `root`, children in the order `next` lists them, so on a graph with extra edges `depth` is the distance from the root. Edge lengths come from the arcs, as in every graph algorithm: `Weighted` arcs (a `w` field, or `g.weighted(f)`) give `dist`, `w` and `diameter` their lengths; others count 1 per edge. The heavy child of a vertex is the child with the largest subtree, the first in child order on ties; `t.Pre` is the preorder that visits the heavy child first and then the other children in child order. - **cost**: O(n + m) for m listed arcs, without recursion - **traps**: when some vertex is not reachable from `root` Examples: - `domain V = 0..5; let adj: [V]List = [[1, 2], [0, 3, 4], [0], [1], [1]]; let t = Rooted(adj, root: 0); t.children(0).collect() == [1, 2] and t.children(1).collect() == [3, 4] and t.depth(4) == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L63) ### `Rooted.from_parents` ```cp fn from_parents(par: [V]?V) -> Rooted ``` Builds a rooted tree from parents keyed by vertex: `par: [V]?V` with `None` at the root, or the usual input shape "parents of 2..n" read as `read<[V.drop(1)]V>()`, whose one missing key is the root. Several roots give a forest, as `forest` does, with the roots in key order. Children are in increasing key order. - **cost**: O(n) - **empty**: a `par` with no root, empty or cyclic, traps - **traps**: when the parents have a cycle; `try_from_parents` is for input that may Examples: - `domain V = 0..3; let par: [V]?V = [None, Some(0), Some(1)]; let t = Rooted.from_parents(par); t.depth(2) == 2 and t.parent(1) == Some(0)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L77) ### `Rooted.try_from_parents` ```cp fn try_from_parents(par: [V]?V) -> ?Rooted ``` `from_parents` for parents that may not form a forest: `None` when they have a cycle. let t = Rooted.try_from_parents(up) else: print("NO"); return - **cost**: O(n) - **empty**: `None` when `par` has no root - **traps**: never Examples: - `domain V = 0..2; let par: [V]?V = [Some(1), Some(0)]; Rooted.try_from_parents(par) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L88) ### `Rooted.forest` ```cp fn forest(next: Next, from: List) -> Rooted ``` One tree per root: `next` must reach every vertex from exactly one of `from`. Each tree is built as `new` builds it. The trees sit one after another in `t.Pre`, in the order of `from`; `t.root` is the first root. Paths and lowest common ancestors exist only within one tree (`root_of` tells). - **cost**: O(n + m) - **empty**: `from` must be nonempty - **traps**: when `from` is empty, or some vertex is reached from no root or from two Examples: - `domain V = 0..4; let adj: [V]List = [[1], [0], [3], [2]]; let t = Rooted.forest(adj, from: [2, 0]); t.roots.collect() == [2, 0] and t.root_of(1) == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L112) ### `Rooted.build` ```cp fn build(next: Next, roots: List) -> Rooted ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L117) ### `Rooted.roots` ```cp fn roots(self) -> yields V ``` The roots in the order given: one for `new`, one per tree for `forest`, key order for `from_parents`. - **cost**: O(1) to make, O(1) per root - **order**: as given at construction - **traps**: never Examples: - `domain V = 0..5; let adj: [V]List = [[1, 2], [0, 3, 4], [0], [1], [1]]; let t = Rooted(adj, root: 0); t.roots.collect() == [0]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L192) ### `Rooted.pos` ```cp fn pos(self, v: V) -> Pre ``` The position of `v` in this tree's own preorder domain `t.Pre`; the inverse of `at`. - **cost**: O(1) - **traps**: never Examples: - `domain V = 0..5; let adj: [V]List = [[1, 2], [0, 3, 4], [0], [1], [1]]; let t = Rooted(adj, root: 0); t.at[t.pos(3)] == 3 and t.pos(1) < t.pos(3) and t.pos(4) < t.pos(2)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L203) ### `Rooted.parent` ```cp fn parent(self, v: V) -> ?V ``` The parent of `v`; `None` at a root. - **cost**: O(1) - **traps**: never Examples: - `domain V = 0..5; let adj: [V]List = [[1, 2], [0, 3, 4], [0], [1], [1]]; let t = Rooted(adj, root: 0); t.parent(3) == Some(1) and t.parent(0) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L210) ### `Rooted.up_arc` ```cp fn up_arc(self, v: V) -> ?A ``` The arc `v` was entered by, with every field `next` gave it (`t.up_arc(v)!.cost` on a tree read with a `cost` field); `None` at a root. Edge data stays on the arcs, so no `[V]` side array is built from the edge list. - **cost**: O(1) - **traps**: never Examples: - `domain V = 0..3; let es: [0..2](u: V, v: V) = [(u: 0, v: 1), (u: 1, v: 2)]; let t = Rooted(Graph.undirected(es), root: 0); t.up_arc(2)!.to == 2 and t.up_arc(0) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L220) ### `Rooted.reorder` ```cp fn reorder(self, a: [V]T) -> [Pre]T ``` Reorders a vertex-indexed array into preorder: `out[t.pos(v)] == a[v]`, ready to build a `SegTree` or `Fenwick` over `t.Pre`. - **cost**: O(n) - **empty**: never empty; a tree has a vertex - **order**: by `t.Pre` - **traps**: never Examples: - `domain V = 0..5; let adj: [V]List = [[1, 2], [0, 3, 4], [0], [1], [1]]; let t = Rooted(adj, root: 0); t.reorder([10, 11, 12, 13, 14]).collect() == [10, 11, 13, 14, 12]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L230) ### `Rooted.children` ```cp fn children(self, v: V) -> yields V ``` The children of `v`, in the order `next` listed them. Children are stored contiguously, so nothing is allocated. - **cost**: O(1) to start, O(1) per child - **empty**: nothing at a leaf - **order**: as `next` listed them - **traps**: never Examples: - `domain V = 0..5; let adj: [V]List = [[1, 2], [0, 3, 4], [0], [1], [1]]; let t = Rooted(adj, root: 0); t.children(1).collect() == [3, 4] and t.children(2).count() == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L240) ### `Rooted.child_arcs` ```cp fn child_arcs(self, v: V) -> yields A ``` The arcs from `v` down to its children, with every field `next` gave them (`for a in t.child_arcs(v): up(a.to) + a.w`), so edge data needs no side array. - **cost**: O(1) per child - **empty**: nothing at a leaf - **order**: child order - **traps**: never Examples: - `domain V = 0..3; let es: [0..2](u: V, v: V) = [(u: 0, v: 1), (u: 1, v: 2)]; let t = Rooted(Graph.undirected(es), root: 0); t.child_arcs(1).map(a => a.to).collect() == [2]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L251) ### `Rooted.excl_fold` ```cp fn excl_fold(self, v: V, op: M, f: V -> T) -> yields (c: V, rest: T) ``` For each child `c` of `v`, in child order, the fold with `op` of `f` over `v`'s other children: the step of a rerooting DP, with no division or inverse. The fold keeps child order (earlier siblings, then later ones), so `op` need not commute; with one child, `rest` is the identity. Prefix and suffix folds make it O(k) for `k` children. for (c, rest) in t.excl_fold(v, mul, c => down[c] + 1): up[c] = (up[v] * rest + 1) % m - **cost**: O(k) calls of `f` and of `op`, O(k) memory - **empty**: nothing at a leaf - **order**: child order - **traps**: never Examples: - `domain V = 0..5; let adj: [V]List = [[1, 2], [0, 3, 4], [0], [1], [1]]; let t = Rooted(adj, root: 0); t.excl_fold(0, add, c => t.size(c)).collect() == [(c: 1, rest: 1), (c: 2, rest: 3)]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L269) ### `Rooted.depth` ```cp fn depth(self, v: V) -> Int ``` The number of edges between `v` and its root. - **cost**: O(1) - **traps**: never Examples: - `domain V = 0..5; let adj: [V]List = [[1, 2], [0, 3, 4], [0], [1], [1]]; let t = Rooted(adj, root: 0); t.depth(0) == 0 and t.depth(4) == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L276) ### `Rooted.size` ```cp fn size(self, v: V) -> Int ``` The number of vertices in the subtree of `v`, `v` included. - **cost**: O(1) - **traps**: never Examples: - `domain V = 0..5; let adj: [V]List = [[1, 2], [0, 3, 4], [0], [1], [1]]; let t = Rooted(adj, root: 0); t.size(0) == 5 and t.size(1) == 3 and t.size(2) == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L283) ### `Rooted.light` ```cp fn light(self, v: V) -> yields V ``` The children of `v` other than its heavy child, in child order. Every vertex has O(log n) light edges above it, which is what small-to-large merging pays for. - **cost**: O(children) - **empty**: nothing at a leaf - **order**: child order - **traps**: never Examples: - `domain V = 0..5; let adj: [V]List = [[1, 2], [0, 3, 4], [0], [1], [1]]; let t = Rooted(adj, root: 0); t.light(0).collect() == [2] and t.light(1).collect() == [4]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L293) ### `Rooted.root_of` ```cp fn root_of(self, v: V) -> V ``` The root of the tree that holds `v`: always `t.root` unless built as a forest. - **cost**: O(log n) - **traps**: never Examples: - `domain V = 0..5; let adj: [V]List = [[1, 2], [0, 3, 4], [0], [1], [1]]; let t = Rooted(adj, root: 0); t.root_of(4) == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L302) ### `Rooted.subtree` ```cp fn subtree(self, v: V) -> yields V ``` The vertices of `v`'s subtree in preorder, `v` first: `t.at[p] for p in t.sub(v)`. - **cost**: O(size(v)) - **empty**: never empty; it holds `v` - **order**: `t.Pre` order - **traps**: never Examples: - `domain V = 0..5; let adj: [V]List = [[1, 2], [0, 3, 4], [0], [1], [1]]; let t = Rooted(adj, root: 0); t.subtree(1).collect() == [1, 3, 4] and t.subtree(0).collect() == [0, 1, 3, 4, 2]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L314) ### `Rooted.down` ```cp fn down(self, init: T, f: (T, V) -> T) -> [V]T ``` A top-down pass: `out[v] = f(out[parent], v)`, and `f(init, r)` at a root `r`. The state on the path from the root, such as a prefix maximum or a distance. - **cost**: O(n) calls of `f` - **empty**: never empty - **order**: keyed by `V`; `f` runs in `t.Pre` order - **traps**: never Examples: - `domain V = 0..5; let adj: [V]List = [[1, 2], [0, 3, 4], [0], [1], [1]]; let t = Rooted(adj, root: 0); t.down(0, (d, v) => d + 1) == [1, 2, 2, 3, 3]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L325) ### `Rooted.up` ```cp fn up( self, op: M, lift: (T, V, V) -> U = (x, c, p) => x, finish: (U, V) -> T, ) -> [V]T ``` A bottom-up tree DP: `out[v] = finish(fold with op of lift(out[c], c, v) over children c, v)`. `lift` sees both ends of the edge, child first, and defaults to the child's value. Children fold in child order, so `op` need not commute; a leaf folds nothing and gets the identity. - **cost**: O(n) calls of `lift`, `op` and `finish` - **empty**: never empty - **order**: keyed by `V` - **traps**: never Examples: - `domain V = 0..5; let adj: [V]List = [[1, 2], [0, 3, 4], [0], [1], [1]]; let t = Rooted(adj, root: 0); t.up(add, finish: (s, v) => s + 1) == [5, 3, 1, 1, 1]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L343) ### `Rooted.reroot` ```cp fn reroot( self, op: M, lift: (T, V, V) -> U = (x, c, p) => x, finish: (U, V) -> T, ) -> [V]T ``` The same DP as `up`, for every root at once: `out[v]` is what `up` would give at `v` if the tree were rooted at `v`. Each vertex folds its parent's side first, then its children in child order; the sibling folds use prefixes and suffixes, so `op` needs no inverse. - **cost**: O(n) calls of `lift` and `finish`, O(n) calls of `op` - **empty**: never empty - **order**: keyed by `V` - **traps**: never Examples: - `domain V = 0..5; let adj: [V]List = [[1, 2], [0, 3, 4], [0], [1], [1]]; let t = Rooted(adj, root: 0); t.reroot(add, lift: (x, c, p) => 1, finish: (s, v) => s) == [2, 3, 1, 1, 1]` - `domain V = 0..5; let adj: [V]List = [[1, 2], [0, 3, 4], [0], [1], [1]]; let t = Rooted(adj, root: 0); t.reroot(add, finish: (s, v) => s + 1) == [5, 5, 5, 5, 5]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L373) ### `Rooted.shapes` ```cp fn shapes(self) -> (domain Shape, of: [V]Shape) ``` The isomorphism class of every subtree: `of[a] == of[b]` exactly when the subtrees of `a` and `b` are the same rooted tree up to reordering children. Classes are numbered in reverse preorder (children before parents) by first appearance, so a leaf, if any, has class `Shape.first`. - **cost**: O(n log n) - **empty**: never empty - **order**: `of` keyed by `V` - **traps**: never Examples: - `domain V = 0..5; let adj: [V]List = [[1, 2], [0, 3, 4], [0], [1], [1]]; let t = Rooted(adj, root: 0); let (domain S, of) = t.shapes(); of[3] == of[2] and of[1] != of[0] and S.count == 3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L421) ### `Rooted.subtree_sizes` ```cp fn subtree_sizes(self) -> [V]Int ``` The size of every subtree, by vertex: `t.subtree_sizes[v] == t.size(v)`. - **cost**: O(1); a view of the stored sizes - **empty**: never empty - **order**: keyed by `V` - **traps**: never Examples: - `domain V = 0..5; let adj: [V]List = [[1, 2], [0, 3, 4], [0], [1], [1]]; let t = Rooted(adj, root: 0); t.subtree_sizes == [5, 3, 1, 1, 1]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L440) ### `Rooted.centroid` ```cp fn centroid(self) -> V ``` A centroid of the tree holding `t.root`: a vertex whose removal leaves no piece of more than half its vertices. Found by walking heavy children down from the root while the heavy child's subtree is more than half. - **cost**: O(depth) - **ties**: of two centroids, the one nearer the root - **traps**: never Examples: - `domain V = 0..5; let adj: [V]List = [[1, 2], [0, 3, 4], [0], [1], [1]]; let t = Rooted(adj, root: 0); t.centroid() == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L451) ### `Rooted.centroids` ```cp fn centroids(self) -> List ``` Every centroid of the tree holding `t.root`, one or two. Two happen only when the number of vertices is even and one edge splits the tree in halves. - **cost**: O(depth) - **empty**: never empty - **order**: the one nearer the root first - **traps**: never Examples: - `domain V = 0..5; let adj: [V]List = [[1, 2], [0, 3, 4], [0], [1], [1]]; let t = Rooted(adj, root: 0); t.centroids() == [1]` - `domain P = 0..4; let adj: [P]List

= [[1], [0, 2], [1, 3], [2]]; Rooted(adj, root: 0).centroids() == [1, 2]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L472) ### `Rooted.tour` ```cp fn tour(self) -> yields Visit ``` The enter/exit Euler tour, the `Visit` events of `std.graph.dfs`: `Enter(v, via:)` when entering `v` and `Exit(v, via:)` when leaving its subtree, `via` the parent (`None` at a root, and a tree has no `Again`), children in `t.Pre` order, each tree of a forest in turn. Iterative, so deep trees are safe. - **cost**: O(1) to make, O(n) to walk - **empty**: never empty - **order**: `Enter` events in `t.Pre` order; `Exit(v, _)` right after the last event of `v`'s subtree - **traps**: never Examples: - `domain V = 0..5; let adj: [V]List = [[1, 2], [0, 3, 4], [0], [1], [1]]; let t = Rooted(adj, root: 0); t.tour.collect() == [Enter(0, None), Enter(1, Some(0)), Enter(3, Some(1)), Exit(3, Some(1)), Enter(4, Some(1)), Exit(4, Some(1)), Exit(1, Some(0)), Enter(2, Some(0)), Exit(2, Some(0)), Exit(0, None)]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L490) ### `Rooted.sub` ```cp fn sub(self, v: V) -> Range

```

The positions of `v`'s subtree, `v` first: one contiguous range of `t.Pre`.

- **cost**: O(1)
- **empty**: never empty; it holds `t.pos(v)`
- **order**: increasing positions
- **traps**: never

Examples:

- `domain V = 0..5; let adj: [V]List = [[1, 2], [0, 3, 4], [0], [1], [1]]; let t = Rooted(adj, root: 0); t.sub(1).map(p => t.at[p]).collect() == [1, 3, 4]`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L512)

### `Rooted.below`

```cp
fn below(self, v: V) -> Range
```

The positions of `v`'s descendants: `sub(v)` without `v`.

- **cost**: O(1)
- **empty**: empty at a leaf
- **order**: increasing positions
- **traps**: never

Examples:

- `domain V = 0..5; let adj: [V]List = [[1, 2], [0, 3, 4], [0], [1], [1]]; let t = Rooted(adj, root: 0); t.below(1).map(p => t.at[p]).collect() == [3, 4] and t.below(2).count() == 0`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L521)

### `Rooted.is_anc`

```cp
fn is_anc(self, a: V, b: V) -> Bool
```

Whether `a` is an ancestor of `b`; a vertex is its own ancestor.

- **cost**: O(1)
- **traps**: never

Examples:

- `domain V = 0..5; let adj: [V]List = [[1, 2], [0, 3, 4], [0], [1], [1]]; let t = Rooted(adj, root: 0); t.is_anc(1, 3) and t.is_anc(3, 3) and not t.is_anc(2, 3)`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L528)

### `Rooted.lower`

```cp
fn lower(self, u: V, v: V) -> V
```

The child end of the tree edge between `u` and `v`, in either order.

- **cost**: O(1)
- **ties**: None; exactly one end is the child
- **traps**: when `u` and `v` are not joined by a tree edge

Examples:

- `domain V = 0..5; let adj: [V]List = [[1, 2], [0, 3, 4], [0], [1], [1]]; let t = Rooted(adj, root: 0); t.lower(0, 1) == 1 and t.lower(3, 1) == 3`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L536)

### `Rooted.lca`

```cp
fn lca(self, a: V, b: V) -> V
```

The lowest common ancestor of `a` and `b`, by heavy-path climbing.

- **cost**: O(log n)
- **traps**: when `a` and `b` are in different trees of a forest

Examples:

- `domain V = 0..5; let adj: [V]List = [[1, 2], [0, 3, 4], [0], [1], [1]]; let t = Rooted(adj, root: 0); t.lca(3, 4) == 1 and t.lca(3, 2) == 0 and t.lca(1, 3) == 1`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L547)

### `Rooted.dist`

```cp
fn dist(self, a: V, b: V) -> Int
```

The length of the path between `a` and `b`: its number of edges, or the total of its edge
lengths in a tree built from `Weighted` arcs.

- **cost**: O(log n)
- **traps**: when `a` and `b` are in different trees of a forest

Examples:

- `domain V = 0..5; let adj: [V]List = [[1, 2], [0, 3, 4], [0], [1], [1]]; let t = Rooted(adj, root: 0); t.dist(3, 2) == 3 and t.dist(4, 4) == 0`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L560)

### `Rooted.path`

```cp
fn path(self, a: V, b: V) -> List
```

The simple path of vertices from `a` to `b`, both included.

- **cost**: O(log n + |path|)
- **empty**: never empty; `[a]` when `a == b`
- **order**: from `a` to `b`
- **traps**: when `a` and `b` are in different trees of a forest

Examples:

- `domain V = 0..5; let adj: [V]List = [[1, 2], [0, 3, 4], [0], [1], [1]]; let t = Rooted(adj, root: 0); t.path(3, 2) == [3, 1, 0, 2] and t.path(4, 4) == [4]`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L569)

### `Rooted.diameter`

```cp
fn diameter(self) -> (len: Int, u: V, v: V)
```

A longest simple path in the tree holding `t.root`: `(len, u, v)` with
`t.dist(u, v) == len`, by two sweeps: `u` is farthest from the root, `v` farthest from `u`.

- **cost**: O(n)
- **ties**: in each sweep the farthest vertex first in `t.Pre` order
- **traps**: never

Examples:

- `domain V = 0..5; let adj: [V]List = [[1, 2], [0, 3, 4], [0], [1], [1]]; let t = Rooted(adj, root: 0); t.diameter() == (len: 3, u: 3, v: 2)`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L592)

### `Rooted.ancestor`

```cp
fn ancestor(self, v: V, k: Int) -> ?V
```

The ancestor `k` edges above `v` (`v` itself for `k == 0`), or `None` if that is above the
root.

- **cost**: O(log n)
- **traps**: when `k` is negative

Examples:

- `domain V = 0..5; let adj: [V]List = [[1, 2], [0, 3, 4], [0], [1], [1]]; let t = Rooted(adj, root: 0); t.ancestor(3, 2) == Some(0) and t.ancestor(3, 3) == None and t.ancestor(3, 0) == Some(3)`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L615)

### `Rooted.jump`

```cp
fn jump(self, a: V, b: V, k: Int) -> ?V
```

The vertex `k` edges from `a` on the path to `b` (`a` for `k == 0`), or `None` if the path
is shorter.

- **cost**: O(log n)
- **traps**: when `k` is negative, or `a` and `b` are in different trees

Examples:

- `domain V = 0..5; let adj: [V]List = [[1, 2], [0, 3, 4], [0], [1], [1]]; let t = Rooted(adj, root: 0); t.jump(3, 2, 2) == Some(0) and t.jump(3, 2, 3) == Some(2) and t.jump(3, 2, 4) == None`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L630)

### `Rooted.jump_while`

```cp
fn jump_while(self, v: V, pred: V -> Bool) -> ?V
```

The highest ancestor `u` of `v` such that `pred(u)` holds, or `None` when `pred(v)` is false.
`pred` must be true and then false on the way up, and is checked only where the search
probes it.

- **cost**: O(log² n) calls of `pred`
- **traps**: never

Examples:

- `domain V = 0..5; let adj: [V]List = [[1, 2], [0, 3, 4], [0], [1], [1]]; let t = Rooted(adj, root: 0); t.jump_while(3, v => v != 0) == Some(1) and t.jump_while(3, v => v == 0) == None`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L646)

### `Rooted.chains`

```cp
fn chains( self, a: V, b: V, edges: Bool = false, ) -> yields (range: Range
, rising: Bool)
```

The path from `a` to `b` as O(log n) heavy-chain ranges of `t.Pre`, in path order. A
`rising` range is walked from its high end to its low end. With `edges`, the highest vertex
of the path is left out: for a value per edge, stored at the edge's lower end.

- **cost**: O(log n) ranges
- **empty**: with `edges` and `a == b`, nothing; otherwise never empty
- **order**: from `a` to `b`
- **traps**: when `a` and `b` are in different trees of a forest

Examples:

- `domain V = 0..5; let adj: [V]List = [[1, 2], [0, 3, 4], [0], [1], [1]]; let t = Rooted(adj, root: 0); t.chains(3, 2).map(c => c.rising).collect() == [true, false] and t.chains(3, 2, edges: true).count() == 2`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L657)

### `Rooted.fold_path`

```cp
fn fold_path(self, a: V, b: V, ds: S, edges: Bool = false) -> T
```

The fold of the values on the path from `a` to `b`, in that order, read from `ds`: any
structure over `t.Pre` with `fold(range)` and a `monoid` (`SegTree`).

A stretch of the path that climbs is folded top-down by `ds` and then turned round with
`rev()`: a value that is not its own reverse implements `Reversible`. With `edges`, the
value at the lowest common ancestor is left out.

- **cost**: O(log² n) with one structure
- **empty**: the identity for `a == b` with `edges`
- **traps**: when `a` and `b` are in different trees of a forest

Examples:

- `domain V = 0..5; let adj: [V]List = [[1, 2], [0, 3, 4], [0], [1], [1]]; let t = Rooted(adj, root: 0); let seg = SegTree(+, t.reorder([1, 2, 4, 8, 16])); t.fold_path(3, 2, seg) == 15 and t.fold_path(3, 2, seg, edges: true) == 14`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L690)

### `Rooted.apply_path`

```cp
fn apply_path(self, a: V, b: V, mut ds: S, tag: F, edges: Bool = false)
```

Applies the update `tag` to every vertex on the path from `a` to `b`, through
`ds.apply(range, tag)` once per chain range. With `edges`, the lowest common ancestor is
left out.

- **cost**: O(log² n)
- **empty**: nothing changes for `a == b` with `edges`
- **traps**: when `a` and `b` are in different trees of a forest

Examples:

- `domain V = 0..5; let adj: [V]List = [[1, 2], [0, 3, 4], [0], [1], [1]]; let t = Rooted(adj, root: 0); var seg = SegTree(+, t.reorder([0, 0, 0, 0, 0]), act: add); t.apply_path(3, 2, seg, 5); t.fold_path(3, 2, seg) == 20 and seg.fold(t.sub(1)) == 10`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L706)

### `Rooted.virtual`

```cp
fn virtual(self, keys: List) -> VirtualTree
```

The tree squeezed down to `keys`: the keys and the lowest common ancestor of every pair, in
a fresh domain `vt.K` in preorder, so `for x in vt.K.rev` visits children first.

`vt.at[x]` is the vertex, `vt.parent[x]` its nearest kept ancestor, `vt.w[x]` the
weighted distance to it (0 at the top) and `vt.key[x]` whether it is a key. Repeated keys
count once.

- **cost**: O(k log k + k log n) for k keys
- **empty**: `keys` empty gives an empty `vt.K`
- **order**: `vt.K` in `t.Pre` order
- **traps**: when the keys are in different trees of a forest

Examples:

- `domain V = 0..5; let adj: [V]List = [[1, 2], [0, 3, 4], [0], [1], [1]]; let t = Rooted(adj, root: 0); let vt = t.virtual([4, 3]); vt.at == [1, 3, 4] and vt.key == [false, true, true] and vt.w == [0, 1, 1]`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L721)

### `Rooted.w`

```cp
fn w(self, v: V) -> Int
```

The edge length from `v` up to its parent: 0 at a root, 1 unless the arcs are `Weighted`.

- **cost**: O(1)
- **traps**: never

Examples:

- `domain V = 0..5; let adj: [V]List = [[1, 2], [0, 3, 4], [0], [1], [1]]; let t = Rooted(adj, root: 0); t.w(3) == 1 and t.w(0) == 0`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L759)

### `Rooted.ancestors`

```cp
fn ancestors(self, v: V) -> yields V
```

`v`, its parent, and so on up to its root.

- **cost**: O(1) per vertex, O(depth(v)) in all
- **empty**: never empty; it starts with `v`
- **order**: from `v` up
- **traps**: never

Examples:

- `domain V = 0..5; let adj: [V]List = [[1, 2], [0, 3, 4], [0], [1], [1]]; let t = Rooted(adj, root: 0); t.ancestors(3).collect() == [3, 1, 0]`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L770)

### `Rooted.top`

```cp
fn top(self, v: V) -> V
```

The top of the heavy chain through `v`: the highest vertex reached by heavy edges.

- **cost**: O(1)
- **ties**: None; the heavy children fix the chain
- **traps**: never

Examples:

- `domain V = 0..5; let adj: [V]List = [[1, 2], [0, 3, 4], [0], [1], [1]]; let t = Rooted(adj, root: 0); t.top(3) == 0 and t.top(4) == 4 and t.top(2) == 2`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L785)

### `Rooted.chain`

```cp
fn chain(self, v: V) -> Range
```

The heavy chain through `v` as one range of positions, its top first.

- **cost**: O(1)
- **empty**: never empty
- **order**: top first, down the chain
- **traps**: never

Examples:

- `domain V = 0..5; let adj: [V]List = [[1, 2], [0, 3, 4], [0], [1], [1]]; let t = Rooted(adj, root: 0); t.chain(3).map(p => t.at[p]).collect() == [0, 1, 3] and t.chain(2).count() == 1`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L795)

### `Rooted.sub_at`

```cp
fn sub_at(self, v: V, root: V) -> yields Range
```

The subtree of `v` were the tree rooted at `root`, as at most two ranges of positions:
`sub(v)` when `root` is outside it, all of `t.Pre` when `v == root`, and otherwise
everything except the subtree of the child of `v` toward `root`.

- **cost**: O(log n)
- **empty**: empty ranges are skipped, so one or two ranges come out
- **order**: increasing positions
- **traps**: when `v` and `root` are in different trees of a forest

Examples:

- `domain V = 0..5; let adj: [V]List = [[1, 2], [0, 3, 4], [0], [1], [1]]; let t = Rooted(adj, root: 0); t.sub_at(1, 3).flat_map(r => r.map(p => t.at[p])).collect() == [0, 1, 4, 2] and t.sub_at(1, 2).count() == 1`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L811)

### `Rooted.on_path`

```cp
fn on_path(self, c: V, a: V, b: V) -> Bool
```

Whether `c` lies on the path from `a` to `b`, ends included.

- **cost**: O(log n)
- **traps**: never

Examples:

- `domain V = 0..5; let adj: [V]List = [[1, 2], [0, 3, 4], [0], [1], [1]]; let t = Rooted(adj, root: 0); t.on_path(1, 3, 2) and t.on_path(3, 3, 2) and not t.on_path(4, 3, 2)`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L819)

### `Rooted.meet`

```cp
fn meet(self, a: V, b: V, c: V) -> V
```

The one vertex on all three paths between `a`, `b` and `c`: the deepest of their pairwise
lowest common ancestors.

- **cost**: O(log n)
- **traps**: when the three are not in one tree

Examples:

- `domain V = 0..5; let adj: [V]List = [[1, 2], [0, 3, 4], [0], [1], [1]]; let t = Rooted(adj, root: 0); t.meet(3, 4, 2) == 1 and t.meet(3, 2, 0) == 0`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L830)

### `Rooted.above`

```cp
fn above( self, op: M, lift: (T, V, V) -> U = (x, c, p) => x, finish: (U, V) -> T, ) -> [V]?T
```

The other half of `reroot`: for `v` that is not a root, the DP of the tree without `sub(v)`,
rooted at `parent(v)`; `None` at a root. Takes the arguments of `reroot`, for answers that
are per edge rather than per vertex.

- **cost**: O(n) calls of `lift` and `finish`, O(n) calls of `op`
- **empty**: never empty
- **order**: keyed by `V`
- **traps**: never

Examples:

- `domain V = 0..5; let adj: [V]List = [[1, 2], [0, 3, 4], [0], [1], [1]]; let t = Rooted(adj, root: 0); t.above(add, finish: (s, v) => s + 1) == [None, Some(2), Some(4), Some(4), Some(4)]`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L845)

### `Rooted.farthest`

```cp
fn farthest( self, x: ?(len: Int, u: V, v: V), y: ?(len: Int, u: V, v: V), ) -> ?(len: Int, u: V, v: V)
```

The farthest pair among two vertex sets' farthest pairs, which is the farthest pair of
their union; `None` is the identity. As an operation value,
`SegTree(op: (x, y) => t.farthest(x, y), id: None)` keeps the diameter of any range of
vertices under changes.

- **cost**: O(log n): at most four `dist` calls
- **ties**: the first longest of `x`, `y`, `(x.u, y.u)`, `(x.u, y.v)`, `(x.v, y.u)`, `(x.v, y.v)`
- **traps**: when the vertices are in different trees of a forest

Examples:

- `domain V = 0..5; let adj: [V]List = [[1, 2], [0, 3, 4], [0], [1], [1]]; let t = Rooted(adj, root: 0); t.farthest(Some((len: 0, u: 3, v: 3)), Some((len: 0, u: 2, v: 2))) == Some((len: 3, u: 3, v: 2)) and t.farthest(None, None) == None`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L890)

### `Rooted.layers`

```cp
fn layers(self) -> Layers
```

Every vertex ordered by depth, each depth in `t.Pre` order, over a fresh domain, so the
descendants of `v` at one depth are one range.

- **cost**: O(n)
- **empty**: never empty
- **order**: by depth, then `t.Pre`
- **traps**: never

Examples:

- `domain V = 0..5; let adj: [V]List = [[1, 2], [0, 3, 4], [0], [1], [1]]; let t = Rooted(adj, root: 0); let ly = t.layers(); ly.level(1).map(b => ly.at[b]).collect() == [1, 2]`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L912)

### `Rooted.events`

```cp
fn events(self) -> Events
```

The 2n enter and exit events of `tour` over a fresh domain, for Mo's algorithm on paths and
on subtrees.

- **cost**: O(n)
- **empty**: never empty
- **order**: `tour` order
- **traps**: never

Examples:

- `domain V = 0..5; let adj: [V]List = [[1, 2], [0, 3, 4], [0], [1], [1]]; let t = Rooted(adj, root: 0); let ev = t.events(); ev.sub(1).count() == 6`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L936)

### `Rooted.euler_tour`

```cp
fn euler_tour(self, by: V -> K = _ => ()) -> yields V
```

The closed Euler walk: 2n - 1 visits from the root back to it, each pair of neighbours
joined by a tree edge, children in `t.Pre` order. `by:` reorders each vertex's children
by a key, stably, so `by: c => c in deep` walks the children in `deep` last. A walk that
visits every vertex of a connected graph is `Rooted(g, root: r).euler_tour()`. A forest
walks only the first tree.

- **cost**: O(1) per item
- **empty**: never empty; `[r]` for a single vertex
- **order**: walk order from the root
- **traps**: never

Examples:

- `domain V = 0..5; let adj: [V]List = [[1, 2], [0, 3, 4], [0], [1], [1]]; let t = Rooted(adj, root: 0); t.euler_tour().collect() == [0, 1, 3, 1, 4, 1, 0, 2, 0]`
- `domain V = 0..3; let adj: [V]List = [[1, 2], [0], [0]]; let t = Rooted(adj, root: 0); t.euler_tour(by: c => c == 1).collect() == [0, 2, 0, 1, 0]`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L951)

### `Rooted.long_paths`

```cp
fn long_paths(self) -> LongPaths
```

The long-path decomposition, for DP indexed by depth merged in O(n) in total. The tallest
child is the first in child order on ties.

- **cost**: O(n)
- **empty**: never empty
- **ties**: the first tallest child in child order
- **traps**: never

Examples:

- `domain V = 0..5; let adj: [V]List = [[1, 2], [0, 3, 4], [0], [1], [1]]; let t = Rooted(adj, root: 0); let lp = t.long_paths(); lp.height == [2, 1, 0, 0, 0] and lp.deep[1] == Some(3)`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L981)

### `Rooted.preorder`

```cp
fn preorder(self, v: V) -> yields Step
```

The subtree of `v` in `t.Pre` order as `std.dp` steps: `step.state` is the vertex,
`step.depth` its depth below `v`, and `step.prune()` skips the rest of its subtree
(decision 126).

- **cost**: O(size(v)), less when pruned
- **empty**: never empty; it starts with `v`
- **order**: `t.Pre` order
- **traps**: never

Examples:

- `domain V = 0..5; let adj: [V]List = [[1, 2], [0, 3, 4], [0], [1], [1]]; let t = Rooted(adj, root: 0); t.preorder(1).map(s => (s.state, s.depth)).collect() == [(1, 0), (3, 1), (4, 1)]`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1022)

## `VirtualTree`

```cp
pub struct VirtualTree
```

A virtual tree from `Rooted.virtual`: a few vertices of a tree and their pairwise lowest
common ancestors, over its own domain `K` in preorder.

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1030)

## `Centroids`

```cp
pub struct Centroids
```

A centroid decomposition: the centroid of the tree, then recursively of each piece left when
it is removed. Every path passes through the centroid ancestor that first separates its
ends, and each vertex has at most log2 n + 1 centroid ancestors, so a question about all
paths through `v` is a loop over `ancestors(v)`.
Built in O(n log n) time and memory without recursion.

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1041)

### `Centroids.anc`

```cp
anc: [V]List<(c: V, dist: Int, branch: V)>
```

For each vertex, every centroid whose piece holds it, nearest first, with the
distance and the neighbour of the centroid it hangs off.

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1047)

### `Centroids.held`

```cp
held: [V]List
```

For each centroid, the vertices of its piece in breadth-first order from it.

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1049)

### `Centroids.new`

```cp
fn new(next: Next) -> Centroids
```

Decomposes the tree given by `next` (as for `Rooted`: a `Graph`, neighbour lists or a fn).

The first centroid is `Rooted(next, root: V.first).centroid()`. Each piece left by removing
a centroid `c` is rooted at its neighbour of `c` and gets the centroid nearer that root, the
pieces taken in the order `next` lists `c`'s neighbours. Built without recursion.

- **cost**: O(n log n) time and memory
- **ties**: of two centroids in a piece, the one nearer the piece's root
- **traps**: when `next` is not a connected tree

Examples:

- `domain V = 0..5; let adj: [V]List = [[1, 2], [0, 3, 4], [0], [1], [1]]; let cd = Centroids(adj); cd.root == 1 and cd.parent(2) == Some(0)`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1061)

### `Centroids.parent`

```cp
fn parent(self, c: V) -> ?V
```

The parent of centroid `c` in the centroid tree; `None` at `cd.root`.

- **cost**: O(1)
- **traps**: never

Examples:

- `domain V = 0..5; let adj: [V]List = [[1, 2], [0, 3, 4], [0], [1], [1]]; let cd = Centroids(adj); cd.parent(0) == Some(1) and cd.parent(1) == None`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1133)

### `Centroids.depth`

```cp
fn depth(self, c: V) -> Int
```

The depth of `c` in the centroid tree, at most log2 n.

- **cost**: O(1)
- **traps**: never

Examples:

- `domain V = 0..5; let adj: [V]List = [[1, 2], [0, 3, 4], [0], [1], [1]]; let cd = Centroids(adj); cd.depth(1) == 0 and cd.depth(3) == 1 and cd.depth(2) == 2`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1140)

### `Centroids.ancestors`

```cp
fn ancestors(self, v: V) -> yields (c: V, dist: Int)
```

Every centroid whose piece holds `v`, with the tree distance from it: `v` itself at distance
0, then up the centroid tree. At most log2 n + 1 entries, no allocation.

- **cost**: O(1) per entry, O(log n) in all
- **empty**: never empty; it starts with `(c: v, dist: 0)`
- **order**: nearest centroid first, up to `cd.root`
- **traps**: never

Examples:

- `domain V = 0..5; let adj: [V]List = [[1, 2], [0, 3, 4], [0], [1], [1]]; let cd = Centroids(adj); cd.ancestors(2).collect() == [(c: 2, dist: 0), (c: 0, dist: 1), (c: 1, dist: 2)]`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1150)

### `Centroids.piece`

```cp
fn piece(self, c: V) -> yields (v: V, dist: Int, branch: V)
```

The piece of centroid `c`: each vertex `v`, its distance from `c`, and `branch`, the
neighbour of `c` on the way to `v` (`c` itself for `v == c`). Pairs in different branches are
exactly the paths whose highest centroid is `c`.

- **cost**: O(size of the piece)
- **empty**: never empty; it starts with `(v: c, dist: 0, branch: c)`
- **order**: breadth-first from `c`, neighbours in the order `next` lists them
- **traps**: never

Examples:

- `domain V = 0..5; let adj: [V]List = [[1, 2], [0, 3, 4], [0], [1], [1]]; let cd = Centroids(adj); cd.piece(0).collect() == [(v: 0, dist: 0, branch: 0), (v: 2, dist: 1, branch: 2)] and cd.piece(1).count() == 5`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1162)

## `Word`

```cp
impl Reversible for Word
```

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1215)

### `Word.rev`

```cp
fn rev(self) -> Word
```

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1216)

## `JumpTree`

```cp
pub struct JumpTree
```

A rooted forest grown one leaf at a time, by skew-binary jump pointers: `add` is O(1),
queries are O(log n), and it keeps three arrays. Every vertex starts as its own root.

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1302)

### `JumpTree.new`

```cp
fn new() -> JumpTree
```

A forest of lone vertices, each its own root.

- **cost**: O(n)
- **traps**: never

Examples:

- `domain V = 0..4; let j = JumpTree(); j.parent(2) == None and j.root_of(2) == 2`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1312)

### `JumpTree.add`

```cp
fn add(mut self, v: V, p: V)
```

Hangs `v`, a lone vertex not yet in any tree, below `p`, setting its skew-binary jump
pointer from `p`'s.

- **cost**: O(1)
- **traps**: when `v` already has a parent, or `v == p`

Examples:

- `domain V = 0..4; var j = JumpTree(); j.add(1, 0); j.add(2, 1); j.add(3, 1); j.parent(2) == Some(1) and j.depth(3) == 2`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1320)

### `JumpTree.parent`

```cp
fn parent(self, v: V) -> ?V
```

The parent of `v`, or `None` at a root.

- **cost**: O(1)
- **traps**: never

Examples:

- `domain V = 0..4; var j = JumpTree(); j.add(1, 0); j.add(2, 1); j.add(3, 1); j.parent(1) == Some(0) and j.parent(0) == None`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1332)

### `JumpTree.depth`

```cp
fn depth(self, v: V) -> Int
```

The number of edges from `v` up to its root.

- **cost**: O(1)
- **traps**: never

Examples:

- `domain V = 0..4; var j = JumpTree(); j.add(1, 0); j.add(2, 1); j.add(3, 1); j.depth(0) == 0 and j.depth(2) == 2`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1339)

### `JumpTree.root_of`

```cp
fn root_of(self, v: V) -> V
```

The root of `v`'s tree.

- **cost**: O(log n)
- **traps**: never

Examples:

- `domain V = 0..4; var j = JumpTree(); j.add(1, 0); j.add(2, 1); j.add(3, 1); j.root_of(3) == 0`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1346)

### `JumpTree.ancestor`

```cp
fn ancestor(self, v: V, k: Int) -> ?V
```

The ancestor `k` edges above `v` (`v` for `k == 0`), or `None` if that is above the root.

- **cost**: O(log n)
- **traps**: when `k` is negative

Examples:

- `domain V = 0..4; var j = JumpTree(); j.add(1, 0); j.add(2, 1); j.add(3, 1); j.ancestor(2, 2) == Some(0) and j.ancestor(2, 3) == None`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1356)

### `JumpTree.lca`

```cp
fn lca(self, a: V, b: V) -> ?V
```

The lowest common ancestor of `a` and `b`, or `None` in different trees.

- **cost**: O(log n)
- **traps**: never

Examples:

- `domain V = 0..4; var j = JumpTree(); j.add(1, 0); j.add(2, 1); j.add(3, 1); j.lca(2, 3) == Some(1) and j.lca(2, 0) == Some(0)`
- `domain V = 0..3; var j = JumpTree(); j.add(1, 0); j.lca(1, 2) == None`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1369)

### `JumpTree.jump_while`

```cp
fn jump_while(self, v: V, pred: V -> Bool) -> ?V
```

The highest ancestor `u` of `v` such that `pred(u)` holds, or `None` when `pred(v)` is false.
`pred` must be true and then false on the way up.

- **cost**: O(log n) calls of `pred`
- **traps**: never

Examples:

- `domain V = 0..4; var j = JumpTree(); j.add(1, 0); j.add(2, 1); j.add(3, 1); j.jump_while(2, v => v != 0) == Some(1) and j.jump_while(2, v => v == 0) == None`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1388)

### `JumpTree.dist`

```cp
fn dist(self, a: V, b: V) -> ?Int
```

The number of edges between `a` and `b`; `None` across trees.

- **cost**: O(log n)
- **traps**: never

Examples:

- `domain V = 0..4; var j = JumpTree(); j.add(1, 0); j.add(2, 1); j.add(3, 1); j.dist(2, 3) == Some(2) and j.dist(0, 0) == Some(0)`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1395)

### `JumpTree.jump`

```cp
fn jump(self, a: V, b: V, k: Int) -> ?V
```

The `k`-th vertex on the path from `a` to `b` (`a` is the 0th); `None` past `b` or across
trees.

- **cost**: O(log n)
- **traps**: when `k` is negative

Examples:

- `domain V = 0..4; var j = JumpTree(); j.add(1, 0); j.add(2, 1); j.add(3, 1); j.jump(2, 3, 1) == Some(1) and j.jump(2, 3, 2) == Some(3) and j.jump(2, 3, 3) == None`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1403)

## `Lift`

```cp
pub struct Lift(op: (T, T) -> T, identity: T)
```

Binary lifting over a fixed forest given by parent links, each carrying a value on the edge
up: O(n log n) build and memory, O(log n) queries. A forest that grows leaf by leaf is a
`JumpTree`; one that changes is a `LinkCut`.

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1408)

### `Lift.new`

```cp
fn new(par: [V]?(V, T), op: (T, T) -> T, identity: T) -> Lift
```

Binary lifting over the forest `par`: `par[v]` is `v`'s parent with the value on the edge
to it, `None` at a root. `op` must be associative with identity `identity`; it need not
commute, since folds run from the lower end up.

- **cost**: O(n log n) time and memory
- **traps**: when the parent links have a cycle

Examples:

- `domain V = 0..4; let par: [V]?(V, Int) = [None, Some((0, 5)), Some((1, 2)), Some((1, 7))]; let l = Lift(par, op: (x, y) => x + y, identity: 0); l.fold(2, up_to: 0) == 7 and l.depth(3) == 2`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1421)

### `Lift.of`

```cp
fn of(next: V -> ?V) -> Lift
```

Lifting over any partial successor function, such as "the next interval a greedy picks":
`Lift.of(i => first_from(iv[i].r))`. `None` ends a chain; the links must form a forest.
Edge values are `()`, so `climb` and `ancestor` are what it is for.

- **cost**: O(n log n) time and memory, n calls of `next`
- **traps**: when the links have a cycle

Examples:

- `domain I = 0..4; let l = Lift.of(i => if i < 3: Some(I(i + 1)) else: None); l.ancestor(0, 3) == Some(3) and l.depth(0) == 3`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1467)

### `Lift.climb`

```cp
fn climb(self, v: V, ok: V -> Bool) -> (steps: Int, at: V)
```

Climbs from `v` while the next vertex up satisfies `ok`, which must hold on a prefix of
every root path: how many edges were climbed and where it stopped. Greedy "jump while the
next one still fits" counts are `Lift.of(next).climb(v, ok).steps`.

- **cost**: O(log n) calls of `ok`
- **traps**: never

Examples:

- `domain V = 0..4; let par: [V]?(V, Int) = [None, Some((0, 5)), Some((1, 2)), Some((1, 7))]; let l = Lift(par, op: (x, y) => x + y, identity: 0); l.climb(2, u => u != 0) == (steps: 1, at: 1) and l.climb(2, u => false) == (steps: 0, at: 2)`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1480)

### `Lift.parent`

```cp
fn parent(self, v: V) -> ?V
```

The parent of `v`, or `None` at a root.

- **cost**: O(1)
- **traps**: never

Examples:

- `domain V = 0..4; let par: [V]?(V, Int) = [None, Some((0, 5)), Some((1, 2)), Some((1, 7))]; let l = Lift(par, op: (x, y) => x + y, identity: 0); l.parent(2) == Some(1) and l.parent(0) == None`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1495)

### `Lift.depth`

```cp
fn depth(self, v: V) -> Int
```

The number of edges from `v` up to its root.

- **cost**: O(1)
- **traps**: never

Examples:

- `domain V = 0..4; let par: [V]?(V, Int) = [None, Some((0, 5)), Some((1, 2)), Some((1, 7))]; let l = Lift(par, op: (x, y) => x + y, identity: 0); l.depth(0) == 0 and l.depth(3) == 2`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1502)

### `Lift.ancestor`

```cp
fn ancestor(self, v: V, k: Int) -> ?V
```

The ancestor `k` edges above `v` (`v` for `k == 0`), or `None` if that is above the root.

- **cost**: O(log n)
- **traps**: when `k` is negative

Examples:

- `domain V = 0..4; let par: [V]?(V, Int) = [None, Some((0, 5)), Some((1, 2)), Some((1, 7))]; let l = Lift(par, op: (x, y) => x + y, identity: 0); l.ancestor(3, 2) == Some(0) and l.ancestor(3, 3) == None`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1509)

### `Lift.lca`

```cp
fn lca(self, a: V, b: V) -> ?V
```

The lowest common ancestor of `a` and `b`, or `None` in different trees.

- **cost**: O(log n)
- **traps**: never

Examples:

- `domain V = 0..4; let par: [V]?(V, Int) = [None, Some((0, 5)), Some((1, 2)), Some((1, 7))]; let l = Lift(par, op: (x, y) => x + y, identity: 0); l.lca(2, 3) == Some(1)`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1522)

### `Lift.fold`

```cp
fn fold(self, v: V, up_to u: V) -> T
```

The fold with `op` of the edge values from `v` up to its ancestor `u`, lowest first;
`identity` when `u == v`.

- **cost**: O(log n) calls of `op`
- **traps**: when `u` is not an ancestor of `v`

Examples:

- `domain V = 0..4; let par: [V]?(V, Int) = [None, Some((0, 5)), Some((1, 2)), Some((1, 7))]; let l = Lift(par, op: (x, y) => x + y, identity: 0); l.fold(2, up_to: 1) == 2 and l.fold(2, up_to: 0) == 7 and l.fold(2, up_to: 2) == 0`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1545)

### `Lift.climb_while`

```cp
fn climb_while(self, v: V, ok: T -> Bool) -> V
```

The highest ancestor `u` of `v` with `ok(self.fold(v, up_to: u))`, or `v` itself; `ok` must
turn false at most once on the way up, and holds for `identity`.

- **cost**: O(log n) calls of `ok` and `op`
- **traps**: never

Examples:

- `domain V = 0..4; let par: [V]?(V, Int) = [None, Some((0, 5)), Some((1, 2)), Some((1, 7))]; let l = Lift(par, op: (x, y) => x + y, identity: 0); l.climb_while(2, s => s <= 5) == 1 and l.climb_while(2, s => s <= 7) == 0`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1562)

## `LinkCut`

```cp
pub struct LinkCut(m: Monoid)
```

A forest that changes: `link` and `cut` edges, re-root anywhere, and fold or set vertex
values along paths, by a link-cut tree (splay trees over preferred paths). Values fold
with `op`; a value that is not its own reverse implements `Reversible`, as for
`Rooted.fold_path`. Every operation is amortized O(log n).

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1577)

### `LinkCut.new`

```cp
fn new(op: M, a: ?[V]T = None) -> LinkCut
```

`V.count` single-vertex trees holding `a`, or the identity of `op` everywhere when `a` is
absent.

- **cost**: O(n)
- **empty**: `a: None` fills every vertex with the identity
- **traps**: never

Examples:

- `domain V = 0..3; var lc = LinkCut(+); lc.get(2) == 0 and not lc.connected(0, 1)`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1593)

### `LinkCut.top`

```cp
fn top(self, x: V) -> Bool
```

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1598)

### `LinkCut.turn`

```cp
fn turn(mut self, x: V)
```

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1601)

### `LinkCut.push`

```cp
fn push(mut self, x: V)
```

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1606)

### `LinkCut.pull`

```cp
fn pull(mut self, x: V)
```

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1615)

### `LinkCut.rotate`

```cp
fn rotate(mut self, x: V)
```

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1621)

### `LinkCut.splay`

```cp
fn splay(mut self, x: V)
```

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1640)

### `LinkCut.access`

```cp
fn access(mut self, x: V) -> V
```

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1657)

### `LinkCut.make_root`

```cp
fn make_root(mut self, v: V)
```

Makes `v` the root of its tree.

- **cost**: amortized O(log n)
- **traps**: never

Examples:

- `domain V = 0..4; let vals: [V]Int = [1, 2, 3, 4]; var lc = LinkCut(+, a: Some(vals)); lc.link(0, 1); lc.link(1, 2); lc.make_root(0); lc.root_of(2) == 0`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1676)

### `LinkCut.root_of`

```cp
fn root_of(mut self, v: V) -> V
```

The root of the tree holding `v`: the last vertex made root there, by `make_root`, `link`,
`lca` or `fold_path`.

- **cost**: amortized O(log n)
- **traps**: never

Examples:

- `domain V = 0..4; let vals: [V]Int = [1, 2, 3, 4]; var lc = LinkCut(+, a: Some(vals)); lc.link(0, 1); lc.link(1, 2); lc.root_of(0) == 2 and lc.root_of(3) == 3`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1686)

### `LinkCut.connected`

```cp
fn connected(mut self, u: V, v: V) -> Bool
```

Whether `u` and `v` are in the same tree.

- **cost**: amortized O(log n)
- **traps**: never

Examples:

- `domain V = 0..4; let vals: [V]Int = [1, 2, 3, 4]; var lc = LinkCut(+, a: Some(vals)); lc.link(0, 1); lc.link(1, 2); lc.connected(0, 2) and not lc.connected(0, 3)`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1701)

### `LinkCut.link`

```cp
fn link(mut self, u: V, v: V)
```

Adds the edge `u`-`v`: `u` becomes the root of its tree, which hangs below `v`, so the
joined tree keeps `v`'s root.

- **cost**: amortized O(log n), with one `root_of` to check the trees differ
- **traps**: when `u` and `v` are already in one tree

Examples:

- `domain V = 0..4; let vals: [V]Int = [1, 2, 3, 4]; var lc = LinkCut(+, a: Some(vals)); lc.link(0, 1); lc.link(1, 2); lc.link(3, 0); lc.connected(3, 2) and lc.root_of(3) == 2`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1709)

### `LinkCut.cut`

```cp
fn cut(mut self, u: V, v: V)
```

Removes the edge `u`-`v`.

- **cost**: amortized O(log n)
- **traps**: when there is no edge `u`-`v`

Examples:

- `domain V = 0..4; let vals: [V]Int = [1, 2, 3, 4]; var lc = LinkCut(+, a: Some(vals)); lc.link(0, 1); lc.link(1, 2); lc.cut(1, 2); not lc.connected(0, 2) and lc.connected(0, 1)`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1719)

### `LinkCut.lca`

```cp
fn lca(mut self, u: V, v: V, root: V) -> ?V
```

The lowest common ancestor of `u` and `v` when their tree is rooted at `root`, which
becomes its root; `None` unless all three are connected.

- **cost**: amortized O(log n)
- **traps**: never

Examples:

- `domain V = 0..4; let vals: [V]Int = [1, 2, 3, 4]; var lc = LinkCut(+, a: Some(vals)); lc.link(0, 1); lc.link(1, 2); lc.lca(0, 2, 1) == Some(1) and lc.root_of(0) == 1 and lc.lca(0, 3, 1) == None`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1733)

### `LinkCut.get`

```cp
fn get(self, v: V) -> T
```

The value at `v`.

- **cost**: O(1)
- **traps**: never

Examples:

- `domain V = 0..4; let vals: [V]Int = [1, 2, 3, 4]; var lc = LinkCut(+, a: Some(vals)); lc.link(0, 1); lc.link(1, 2); lc.get(2) == 3`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1744)

### `LinkCut.set`

```cp
fn set(mut self, v: V, x: T)
```

Sets the value at `v` to `x`.

- **cost**: amortized O(log n)
- **traps**: never

Examples:

- `domain V = 0..4; let vals: [V]Int = [1, 2, 3, 4]; var lc = LinkCut(+, a: Some(vals)); lc.link(0, 1); lc.link(1, 2); lc.set(2, 10); lc.get(2) == 10 and lc.fold_path(0, 2) == 13`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1751)

### `LinkCut.fold_path`

```cp
fn fold_path(mut self, u: V, v: V) -> T
```

The fold of the values on the path from `u` to `v`, in that order; `u` becomes the root.

- **cost**: amortized O(log n)
- **traps**: when `u` and `v` are in different trees

Examples:

- `domain V = 0..4; let vals: [V]Int = [1, 2, 3, 4]; var lc = LinkCut(+, a: Some(vals)); lc.link(0, 1); lc.link(1, 2); lc.fold_path(0, 2) == 6 and lc.root_of(2) == 0 and lc.fold_path(1, 1) == 2`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1761)

### `LinkCut.dist`

```cp
fn dist(mut self, a: V, b: V) -> ?Int
```

The number of edges between `a` and `b`; `None` across trees.

- **cost**: amortized O(log n)
- **traps**: never

Examples:

- `domain V = 0..4; let vals: [V]Int = [1, 2, 3, 4]; var lc = LinkCut(+, a: Some(vals)); lc.link(0, 1); lc.link(1, 2); lc.dist(0, 2) == Some(2) and lc.dist(0, 3) == None`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1771)

### `LinkCut.jump`

```cp
fn jump(mut self, a: V, b: V, k: Int) -> ?V
```

The `k`-th vertex on the path from `a` to `b` (`a` is the 0th); `None` past `b` or across
trees.

- **cost**: amortized O(log n)
- **traps**: when `k` is negative

Examples:

- `domain V = 0..4; let vals: [V]Int = [1, 2, 3, 4]; var lc = LinkCut(+, a: Some(vals)); lc.link(0, 1); lc.link(1, 2); lc.jump(0, 2, 1) == Some(1) and lc.jump(0, 2, 0) == Some(0) and lc.jump(0, 2, 3) == None`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1779)

## `PreferredPaths`

```cp
pub struct PreferredPaths
```

`LinkCut` with updates along a path: `LazyLinkCut(act, a)` with an add `Action` adds to every value on
a path and folds paths, under the same `Action` as `SegTree(op, a, act:)`. Reversing a path must not
change how a tag acts, `apply(f, x.rev(), k) == apply(f, x, k).rev()`, which holds for every
commutative `over`. Every operation is amortized O(log n). Memory is about twice `LinkCut`'s.
The preferred-path half of a link-cut tree over a fixed rooted tree: every node starts as its
own path. Counting "how many paths lie between v and the root" (colours painted along root
paths, access counts) reads off the switches each `access` makes.

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1788)

### `PreferredPaths.new`

```cp
fn new

(t: Rooted) -> PreferredPaths ``` The preferred paths of `t` with every vertex its own path. - **cost**: O(n) - **traps**: never Examples: - `domain V = 0..5; let adj: [V]List = [[1, 2], [0, 3, 4], [0], [1], [1]]; let t = Rooted(adj, root: 0); var pp = PreferredPaths(t); pp.access(0).count() == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1794) ### `PreferredPaths.access` ```cp fn access(mut self, v: V) -> yields (lost: ?V, gained: V) ``` Makes the path from the root to `v` one preferred path, yielding each switch bottom-up: `gained` is the top vertex of the path just joined to its parent, `lost` the top vertex of the path that parent stopped preferring, if any. Counting "how many paths lie between `v` and the root" reads off the switches. - **cost**: amortized O(log n) switches - **empty**: nothing when `v` is already on the root's preferred path - **order**: bottom-up - **traps**: never Examples: - `domain V = 0..5; let adj: [V]List = [[1, 2], [0, 3, 4], [0], [1], [1]]; let t = Rooted(adj, root: 0); var pp = PreferredPaths(t); pp.access(3).collect() == [(lost: None, gained: 3), (lost: None, gained: 1)] and pp.access(4).collect() == [(lost: Some(3), gained: 4)]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1806) ## `LazyLinkCut` ```cp pub struct LazyLinkCut(act: Action) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1808) ### `LazyLinkCut.cnt` ```cp cnt: [V]0..=V.count ``` The number of vertices in the splay subtree, the `span` that `apply` sees. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1816) ### `LazyLinkCut.new` ```cp fn new(act: Action, a: ?[V]T = None) -> LazyLinkCut ``` `V.count` single-vertex trees holding `a`, or the identity of `act.over` everywhere when `a` is absent. - **cost**: O(n) - **empty**: `a: None` fills every vertex with the identity - **traps**: never Examples: - `domain V = 0..3; var lc = LazyLinkCut(Action(apply: (d, x, n) => x + d * n)); lc.get(1) == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1827) ### `LazyLinkCut.top` ```cp fn top(self, x: V) -> Bool ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1842) ### `LazyLinkCut.turn` ```cp fn turn(mut self, x: V) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1845) ### `LazyLinkCut.put` ```cp fn put(mut self, x: V, f: F) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1850) ### `LazyLinkCut.push` ```cp fn push(mut self, x: V) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1855) ### `LazyLinkCut.pull` ```cp fn pull(mut self, x: V) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1868) ### `LazyLinkCut.rotate` ```cp fn rotate(mut self, x: V) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1880) ### `LazyLinkCut.splay` ```cp fn splay(mut self, x: V) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1899) ### `LazyLinkCut.access` ```cp fn access(mut self, x: V) -> V ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1914) ### `LazyLinkCut.make_root` ```cp fn make_root(mut self, v: V) ``` Makes `v` the root of its tree. - **cost**: amortized O(log n) - **traps**: never Examples: - `domain V = 0..3; let vals: [V]Int = [1, 2, 3]; var lc = LazyLinkCut(Action(apply: (d, x, n) => x + d * n), a: Some(vals)); lc.link(0, 1); lc.link(1, 2); lc.make_root(0); lc.root_of(2) == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1933) ### `LazyLinkCut.root_of` ```cp fn root_of(mut self, v: V) -> V ``` The root of the tree holding `v`, as for `LinkCut.root_of`. - **cost**: amortized O(log n) - **traps**: never Examples: - `domain V = 0..3; let vals: [V]Int = [1, 2, 3]; var lc = LazyLinkCut(Action(apply: (d, x, n) => x + d * n), a: Some(vals)); lc.link(0, 1); lc.link(1, 2); lc.root_of(0) == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1942) ### `LazyLinkCut.connected` ```cp fn connected(mut self, u: V, v: V) -> Bool ``` Whether `u` and `v` are in the same tree. - **cost**: amortized O(log n) - **traps**: never Examples: - `domain V = 0..3; let vals: [V]Int = [1, 2, 3]; var lc = LazyLinkCut(Action(apply: (d, x, n) => x + d * n), a: Some(vals)); lc.link(0, 1); lc.link(1, 2); lc.connected(0, 2)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1957) ### `LazyLinkCut.link` ```cp fn link(mut self, u: V, v: V) ``` Adds the edge `u`-`v` as `LinkCut.link` does: `u`'s tree hangs below `v`. - **cost**: amortized O(log n), with one `root_of` to check the trees differ - **traps**: when `u` and `v` are already in one tree Examples: - `domain V = 0..3; let vals: [V]Int = [1, 2, 3]; var lc = LazyLinkCut(Action(apply: (d, x, n) => x + d * n), a: Some(vals)); lc.link(0, 1); lc.link(1, 2); lc.connected(0, 2) and lc.dist(0, 2) == Some(2)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1964) ### `LazyLinkCut.cut` ```cp fn cut(mut self, u: V, v: V) ``` Removes the edge `u`-`v`. - **cost**: amortized O(log n) - **traps**: when there is no edge `u`-`v` Examples: - `domain V = 0..3; let vals: [V]Int = [1, 2, 3]; var lc = LazyLinkCut(Action(apply: (d, x, n) => x + d * n), a: Some(vals)); lc.link(0, 1); lc.link(1, 2); lc.cut(0, 1); not lc.connected(0, 2) and lc.connected(1, 2)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1974) ### `LazyLinkCut.lca` ```cp fn lca(mut self, u: V, v: V, root: V) -> ?V ``` The lowest common ancestor of `u` and `v` when their tree is rooted at `root`, which becomes its root; `None` unless all three are connected. - **cost**: amortized O(log n) - **traps**: never Examples: - `domain V = 0..3; let vals: [V]Int = [1, 2, 3]; var lc = LazyLinkCut(Action(apply: (d, x, n) => x + d * n), a: Some(vals)); lc.link(0, 1); lc.link(1, 2); lc.lca(0, 2, 1) == Some(1)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1988) ### `LazyLinkCut.get` ```cp fn get(mut self, v: V) -> T ``` The value at `v`, with every update along paths through it applied. - **cost**: amortized O(log n) - **traps**: never Examples: - `domain V = 0..3; let vals: [V]Int = [1, 2, 3]; var lc = LazyLinkCut(Action(apply: (d, x, n) => x + d * n), a: Some(vals)); lc.link(0, 1); lc.link(1, 2); lc.apply_path(0, 1, 10); lc.get(1) == 12 and lc.get(2) == 3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L1999) ### `LazyLinkCut.set` ```cp fn set(mut self, v: V, x: T) ``` Sets the value at `v` to `x`, replacing every earlier update there. - **cost**: amortized O(log n) - **traps**: never Examples: - `domain V = 0..3; let vals: [V]Int = [1, 2, 3]; var lc = LazyLinkCut(Action(apply: (d, x, n) => x + d * n), a: Some(vals)); lc.link(0, 1); lc.link(1, 2); lc.set(1, 7); lc.fold_path(0, 2) == 11` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2008) ### `LazyLinkCut.fold_path` ```cp fn fold_path(mut self, u: V, v: V) -> T ``` The fold of the values on the path from `u` to `v`, in that order; `u` becomes the root. - **cost**: amortized O(log n) - **traps**: when `u` and `v` are in different trees Examples: - `domain V = 0..3; let vals: [V]Int = [1, 2, 3]; var lc = LazyLinkCut(Action(apply: (d, x, n) => x + d * n), a: Some(vals)); lc.link(0, 1); lc.link(1, 2); lc.fold_path(0, 2) == 6` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2018) ### `LazyLinkCut.apply_path` ```cp fn apply_path(mut self, u: V, v: V, f: F) ``` Applies `f` to every value on the path from `u` to `v`; `u` becomes the root. - **cost**: amortized O(log n) - **traps**: when `u` and `v` are in different trees Examples: - `domain V = 0..3; let vals: [V]Int = [1, 2, 3]; var lc = LazyLinkCut(Action(apply: (d, x, n) => x + d * n), a: Some(vals)); lc.link(0, 1); lc.link(1, 2); lc.apply_path(0, 1, 10); lc.fold_path(0, 2) == 26` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2028) ### `LazyLinkCut.dist` ```cp fn dist(mut self, a: V, b: V) -> ?Int ``` The number of edges between `a` and `b`; `None` across trees. - **cost**: amortized O(log n) - **traps**: never Examples: - `domain V = 0..3; let vals: [V]Int = [1, 2, 3]; var lc = LazyLinkCut(Action(apply: (d, x, n) => x + d * n), a: Some(vals)); lc.link(0, 1); lc.link(1, 2); lc.dist(0, 2) == Some(2) and lc.dist(1, 1) == Some(0)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2038) ### `LazyLinkCut.jump` ```cp fn jump(mut self, a: V, b: V, k: Int) -> ?V ``` The `k`-th vertex on the path from `a` to `b` (`a` is the 0th); `None` past `b` or across trees. - **cost**: amortized O(log n) - **traps**: when `k` is negative Examples: - `domain V = 0..3; let vals: [V]Int = [1, 2, 3]; var lc = LazyLinkCut(Action(apply: (d, x, n) => x + d * n), a: Some(vals)); lc.link(0, 1); lc.link(1, 2); lc.jump(2, 0, 1) == Some(1) and lc.jump(2, 0, 3) == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2046) ## `PermKind` ```cp pub enum PermKind = Leaf | Incr | Decr | Partial | Full ``` How a permutation-tree node joins its two children `l` (earlier positions) and `r`. `Incr`: `r`'s values sit just above `l`'s; `Decr`: just below; `Partial`: the union is not an interval on its own and only closes further up; `Full`: `r` fills the gaps of a `Partial` `l`, closing an interval in neither order. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2134) ### `PermKind.Leaf` ```cp Leaf ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2134) ### `PermKind.Incr` ```cp Incr ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2134) ### `PermKind.Decr` ```cp Decr ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2134) ### `PermKind.Partial` ```cp Partial ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2134) ### `PermKind.Full` ```cp Full ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2134) ## `PermNode` ```cp pub enum PermNode: Leaf(i: I), Inner(l: N, r: N, kind ``` A permutation-tree node as `PermTree.node` shows it: `Leaf(i)` for position `i`, or `Inner(l, r, kind)` with its two children and how they join. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2137) ### `PermNode.Leaf` ```cp Leaf(i: I) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2137) ### `PermNode.Inner` ```cp Inner(l: N, r: N, kind: PermKind) ``` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2137) ## `PermTree` ```cp pub struct PermTree ``` The binary permutation (interval-decomposition) tree of a bijection `p: [I]V`: every node covers a run of positions, leaves are single positions, a node's children split its run in two, and the values of every node but a `Partial` one form an interval. Nodes have their own domain `t.Node` of 2n - 1 members; `kind`, `first`, `last`, `lo` and `hi` are arrays over it. Built in O(n) by one stack pass. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2144) ### `PermTree.new` ```cp fn new(p: [I]V) -> PermTree ``` The binary permutation tree of `p`, built by one stack pass from left to right: a run that keeps extending in one direction builds left-deep, so `[0, 1, 2]` is `((0, 1), 2)`. - **cost**: O(n) - **empty**: `I` must be nonempty - **traps**: when `I` is empty, `I.count != V.count`, or `p` is not a bijection Examples: - `domain I = 0..3; let p: [I]I = [1, 0, 2]; let pt = PermTree(p); pt.kind[pt.root] == PermKind.Incr and pt.kind[pt.left(pt.root)] == PermKind.Decr` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2161) ### `PermTree.node` ```cp fn node(self, v: Node) -> PermNode ``` The view of `v` to match on (decision 132): `Leaf(i)` or `Inner(l, r, kind)`. - **cost**: O(1) - **traps**: never Examples: - `domain I = 0..3; let p: [I]I = [1, 0, 2]; let pt = PermTree(p); pt.node(pt.leaf(1)) == PermNode.Leaf(1) and pt.node(pt.root) == PermNode.Inner(pt.left(pt.root), pt.leaf(2), PermKind.Incr)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2168) ### `PermTree.leaf` ```cp fn leaf(self, i: I) -> Node ``` The leaf of position `i`. - **cost**: O(1) - **traps**: never Examples: - `domain I = 0..3; let p: [I]I = [1, 0, 2]; let pt = PermTree(p); pt.span(pt.leaf(2)) == 2..3 and pt.kind[pt.leaf(2)] == PermKind.Leaf` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2175) ### `PermTree.left` ```cp fn left(self, v: Node) -> Node ``` The earlier child of the inner node `v`. - **cost**: O(1) - **traps**: when `v` is a leaf Examples: - `domain I = 0..3; let p: [I]I = [1, 0, 2]; let pt = PermTree(p); pt.span(pt.left(pt.root)) == 0..2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2182) ### `PermTree.right` ```cp fn right(self, v: Node) -> Node ``` The later child of the inner node `v`. - **cost**: O(1) - **traps**: when `v` is a leaf Examples: - `domain I = 0..3; let p: [I]I = [1, 0, 2]; let pt = PermTree(p); pt.right(pt.root) == pt.leaf(2)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2191) ### `PermTree.span` ```cp fn span(self, v: Node) -> Range ``` The positions `v` covers, a nonempty range of `I`. - **cost**: O(1) - **empty**: never empty - **order**: increasing positions - **traps**: never Examples: - `domain I = 0..3; let p: [I]I = [1, 0, 2]; let pt = PermTree(p); pt.span(pt.root) == 0..3` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2202) ### `PermTree.vals` ```cp fn vals(self, v: Node) -> Range ``` From the least to the greatest value `v` covers: exactly its values unless `v` is `Partial`. - **cost**: O(1) - **empty**: never empty - **order**: increasing values - **traps**: never Examples: - `domain I = 0..3; let p: [I]I = [1, 0, 2]; let pt = PermTree(p); pt.vals(pt.left(pt.root)) == 0..2 and pt.vals(pt.leaf(0)) == 1..2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2211) ## `Layers` ```cp pub struct Layers ``` The vertices of a `Rooted` tree by depth, each depth in preorder, over their own domain `B`: the descendants of a vertex at one depth are a contiguous range of `B`. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2221) ### `Layers.start` ```cp start: List ``` The layer of depth `d` is `start[d]..start[d + 1]` as ordinals of `B`. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2225) ### `Layers.pos` ```cp fn pos(self, v: V) -> B ``` The position of `v` among the layers. - **cost**: O(1) - **traps**: never Examples: - `domain V = 0..5; let adj: [V]List = [[1, 2], [0, 3, 4], [0], [1], [1]]; let t = Rooted(adj, root: 0); let ly = t.layers(); ly.at[ly.pos(2)] == 2` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2232) ### `Layers.level` ```cp fn level(self, d: Int) -> Range ``` Every vertex at depth `d`, in `t.Pre` order; empty past the deepest or below 0. - **cost**: O(1) - **empty**: for `d` outside `0..=` the greatest depth - **order**: `t.Pre` order - **traps**: never Examples: - `domain V = 0..5; let adj: [V]List = [[1, 2], [0, 3, 4], [0], [1], [1]]; let t = Rooted(adj, root: 0); let ly = t.layers(); ly.level(2).map(b => ly.at[b]).collect() == [3, 4] and ly.level(3).count() == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2241) ### `Layers.below` ```cp fn below(self, v: V, d: Int) -> Range ``` The descendants of `v` at depth `d`, counted from the root as in `level`, by binary search in `level(d)`; `v` itself when `d == depth(v)`. - **cost**: O(log n) - **empty**: when there are None, including `d < depth(v)` - **order**: `t.Pre` order - **traps**: never Examples: - `domain V = 0..5; let adj: [V]List = [[1, 2], [0, 3, 4], [0], [1], [1]]; let t = Rooted(adj, root: 0); let ly = t.layers(); ly.below(1, 2).map(b => ly.at[b]).collect() == [3, 4] and ly.below(2, 2).count() == 0` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2253) ## `Events` ```cp pub struct Events ``` The enter and exit events of a `Rooted` tree's `tour` over their own domain `P` of 2n members, for Mo's algorithm on trees. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2257) ### `Events.enter` ```cp fn enter(self, v: V) -> P ``` The event that enters `v`. - **cost**: O(1) - **traps**: never Examples: - `domain V = 0..5; let adj: [V]List = [[1, 2], [0, 3, 4], [0], [1], [1]]; let t = Rooted(adj, root: 0); let ev = t.events(); ev.at[ev.enter(1)] == Enter(1, Some(0)) and ev.enter(1) < ev.enter(3)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2265) ### `Events.exit` ```cp fn exit(self, v: V) -> P ``` The event that leaves `v`. - **cost**: O(1) - **traps**: never Examples: - `domain V = 0..5; let adj: [V]List = [[1, 2], [0, 3, 4], [0], [1], [1]]; let t = Rooted(adj, root: 0); let ev = t.events(); ev.at[ev.exit(3)] == Exit(3, Some(1)) and ev.exit(3) < ev.exit(1)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2272) ### `Events.sub` ```cp fn sub(self, v: V) -> Range

``` The events inside `v`'s subtree, `enter(v)` through `exit(v)`. - **cost**: O(1) - **empty**: never empty; 2 * size(v) events - **order**: `tour` order - **traps**: never Examples: - `domain V = 0..5; let adj: [V]List = [[1, 2], [0, 3, 4], [0], [1], [1]]; let t = Rooted(adj, root: 0); let ev = t.events(); ev.sub(1).map(p => ev.at[p]).collect() == [Enter(1, Some(0)), Enter(3, Some(1)), Exit(3, Some(1)), Enter(4, Some(1)), Exit(4, Some(1)), Exit(1, Some(0))]` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2281) ### `Events.path` ```cp fn path(self, a: V, b: V) -> (range: Range

, extra: ?V) ``` A range of events whose vertices met an odd number of times, plus `extra` when present, are exactly the vertices of the path from `a` to `b`. With `a` the end entered first: when `a` is an ancestor of `b`, the range is `enter(a)` through `enter(b)` and `extra` is `None`; otherwise it is `exit(a)` through `enter(b)` and `extra` is their lowest common ancestor. - **cost**: O(log n) - **empty**: never empty - **order**: `tour` order - **traps**: when `a` and `b` are in different trees Examples: - `domain V = 0..5; let adj: [V]List = [[1, 2], [0, 3, 4], [0], [1], [1]]; let t = Rooted(adj, root: 0); let ev = t.events(); ev.path(3, 2).range.count() == 5 and ev.path(3, 2).extra == Some(0) and ev.path(1, 4).extra == None` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2295) ## `LongPaths` ```cp pub struct LongPaths ``` The long-path decomposition of a `Rooted` tree: each vertex continues the path of its tallest child, so a DP indexed by depth below `v` lives in one shared buffer over `L`, inheriting `deep[v]`'s values is free, and merging the other children costs their heights. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2300) ### `LongPaths.deep` ```cp deep: [V]?V ``` The child with the tallest subtree; `None` at a leaf. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2302) ### `LongPaths.height` ```cp height: [V]Int ``` The number of edges on the longest path down from `v`. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2304) ### `LongPaths.slots` ```cp fn slots(self, v: V) -> Range ``` The slots of `v`, one per depth offset `0..=height[v]`, offset 0 first; `slots(deep[v])` starts one later in the same buffer. - **cost**: O(1) - **empty**: never empty - **order**: offset 0 first - **traps**: never Examples: - `domain V = 0..5; let adj: [V]List = [[1, 2], [0, 3, 4], [0], [1], [1]]; let t = Rooted(adj, root: 0); let lp = t.long_paths(); lp.slots(0).count() == 3 and lp.slots(2).count() == 1` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2315) ### `LongPaths.slot` ```cp fn slot(self, v: V, d: Int) -> L ``` The slot of `v` at depth offset `d`. - **cost**: O(1) - **traps**: unless `0 <= d <= height[v]` Examples: - `domain V = 0..5; let adj: [V]List = [[1, 2], [0, 3, 4], [0], [1], [1]]; let t = Rooted(adj, root: 0); let lp = t.long_paths(); lp.slot(1, 1) == lp.slot(3, 0) and lp.slot(0, 1) == lp.slot(1, 0)` [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2322) ## `LcaTable` ```cp pub struct LcaTable ``` Lowest common ancestors in O(1) after O(n log n) preprocessing, by a sparse table over the Euler tour: for many queries on a fixed tree when `Rooted.lca` is the bottleneck. [Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2328) ### `LcaTable.new` ```cp fn new

(t: Rooted) -> LcaTable
```

A sparse table over the Euler walk of `t`, for O(1) lowest common ancestors on a fixed tree.

- **cost**: O(n log n) time and memory
- **traps**: never

Examples:

- `domain V = 0..5; let adj: [V]List = [[1, 2], [0, 3, 4], [0], [1], [1]]; let t = Rooted(adj, root: 0); let lt = LcaTable(t); lt.lca(3, 4) == 1`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2337)

### `LcaTable.lca`

```cp
fn lca(self, a: V, b: V) -> V
```

The lowest common ancestor of `a` and `b`.

- **cost**: O(1)
- **traps**: when `a` and `b` are in different trees

Examples:

- `domain V = 0..5; let adj: [V]List = [[1, 2], [0, 3, 4], [0], [1], [1]]; let t = Rooted(adj, root: 0); let lt = LcaTable(t); lt.lca(3, 2) == 0 and lt.lca(4, 4) == 4`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2344)

### `LcaTable.dist`

```cp
fn dist(self, a: V, b: V) -> Int
```

The distance between `a` and `b`, weighted as the tree was built.

- **cost**: O(1)
- **traps**: when `a` and `b` are in different trees

Examples:

- `domain V = 0..5; let adj: [V]List = [[1, 2], [0, 3, 4], [0], [1], [1]]; let t = Rooted(adj, root: 0); let lt = LcaTable(t); lt.dist(3, 2) == 3`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2351)

## `EulerTourTree`

```cp
pub struct EulerTourTree
```

A forest that changes, with folds over whole trees and subtrees, by an Euler tour tree
(a balanced sequence of each tree's tour). Where `LinkCut` folds paths, this folds
components. Values fold with `op`, which must commute. Every operation is expected
O(log n).

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2357)

### `EulerTourTree.new`

```cp
fn new(op: M, a: ?[V]T = None) -> EulerTourTree
```

Lone vertices with values `a`, or the identity of `op` everywhere when `a` is `None`.

- **cost**: O(n)
- **empty**: `a: None` fills every vertex with the identity
- **traps**: never

Examples:

- `domain V = 0..3; var et = EulerTourTree(+); et.get(1) == 0 and et.len(1) == 1`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2366)

### `EulerTourTree.link`

```cp
fn link(mut self, u: V, v: V)
```

Joins the trees of `u` and `v` by the edge `u`-`v`.

- **cost**: expected O(log n)
- **traps**: when `u` and `v` are already in one tree

Examples:

- `domain V = 0..4; let vals: [V]Int = [1, 2, 3, 4]; var et = EulerTourTree(+, a: Some(vals)); et.link(0, 1); et.link(1, 2); et.connected(0, 2) and et.len(2) == 3`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2373)

### `EulerTourTree.cut`

```cp
fn cut(mut self, u: V, v: V)
```

Removes the edge `u`-`v`.

- **cost**: expected O(log n)
- **traps**: when there is no edge `u`-`v`

Examples:

- `domain V = 0..4; let vals: [V]Int = [1, 2, 3, 4]; var et = EulerTourTree(+, a: Some(vals)); et.link(0, 1); et.link(1, 2); et.cut(1, 2); not et.connected(0, 2) and et.len(0) == 2`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2380)

### `EulerTourTree.connected`

```cp
fn connected(mut self, a: V, b: V) -> Bool
```

Whether `a` and `b` are in one tree.

- **cost**: expected O(log n)
- **traps**: never

Examples:

- `domain V = 0..4; let vals: [V]Int = [1, 2, 3, 4]; var et = EulerTourTree(+, a: Some(vals)); et.link(0, 1); et.link(1, 2); et.connected(0, 2) and not et.connected(0, 3)`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2387)

### `EulerTourTree.len`

```cp
fn len(mut self, v: V) -> Int
```

The number of vertices in `v`'s tree.

- **cost**: expected O(log n)
- **traps**: never

Examples:

- `domain V = 0..4; let vals: [V]Int = [1, 2, 3, 4]; var et = EulerTourTree(+, a: Some(vals)); et.link(0, 1); et.link(1, 2); et.len(0) == 3 and et.len(3) == 1`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2394)

### `EulerTourTree.get`

```cp
fn get(self, v: V) -> T
```

The value at `v`.

- **cost**: O(1)
- **traps**: never

Examples:

- `domain V = 0..4; let vals: [V]Int = [1, 2, 3, 4]; var et = EulerTourTree(+, a: Some(vals)); et.link(0, 1); et.link(1, 2); et.get(3) == 4`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2401)

### `EulerTourTree.set`

```cp
fn set(mut self, v: V, x: T)
```

Replaces the value at `v`.

- **cost**: expected O(log n)
- **traps**: never

Examples:

- `domain V = 0..4; let vals: [V]Int = [1, 2, 3, 4]; var et = EulerTourTree(+, a: Some(vals)); et.link(0, 1); et.link(1, 2); et.set(0, 10); et.fold_tree(2) == 15`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2408)

### `EulerTourTree.fold_tree`

```cp
fn fold_tree(mut self, v: V) -> T
```

The fold of every value in `v`'s tree.

- **cost**: expected O(log n)
- **traps**: never

Examples:

- `domain V = 0..4; let vals: [V]Int = [1, 2, 3, 4]; var et = EulerTourTree(+, a: Some(vals)); et.link(0, 1); et.link(1, 2); et.fold_tree(0) == 6 and et.fold_tree(3) == 4`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2415)

### `EulerTourTree.fold_sub`

```cp
fn fold_sub(mut self, v: V, away: V) -> T
```

The fold over `v`'s side of the edge `v`-`away`: what `v`'s tree would hold were the edge
cut.

- **cost**: expected O(log n)
- **traps**: when there is no edge `v`-`away`

Examples:

- `domain V = 0..4; let vals: [V]Int = [1, 2, 3, 4]; var et = EulerTourTree(+, a: Some(vals)); et.link(0, 1); et.link(1, 2); et.fold_sub(1, 2) == 3 and et.fold_sub(2, 1) == 3`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2423)

## `LazyEulerTourTree`

```cp
pub struct LazyEulerTourTree
```

`EulerTourTree` with updates to whole trees and subtrees under an action.

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2426)

### `LazyEulerTourTree.new`

```cp
fn new(act: Action, a: ?[V]T = None) -> LazyEulerTourTree
```

Lone vertices with values `a`, or the identity of `act.over` everywhere when `a` is `None`.

- **cost**: O(n)
- **empty**: `a: None` fills every vertex with the identity
- **traps**: never

Examples:

- `domain V = 0..3; var et = LazyEulerTourTree(Action(apply: (d, x, n) => x + d * n)); et.get(1) == 0`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2435)

### `LazyEulerTourTree.link`

```cp
fn link(mut self, u: V, v: V)
```

Joins the trees of `u` and `v` by the edge `u`-`v`.

- **cost**: expected O(log n)
- **traps**: when `u` and `v` are already in one tree

Examples:

- `domain V = 0..4; let vals: [V]Int = [1, 2, 3, 4]; var et = LazyEulerTourTree(Action(apply: (d, x, n) => x + d * n), a: Some(vals)); et.link(0, 1); et.link(1, 2); et.connected(0, 2) and et.len(2) == 3`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2442)

### `LazyEulerTourTree.cut`

```cp
fn cut(mut self, u: V, v: V)
```

Removes the edge `u`-`v`.

- **cost**: expected O(log n)
- **traps**: when there is no edge `u`-`v`

Examples:

- `domain V = 0..4; let vals: [V]Int = [1, 2, 3, 4]; var et = LazyEulerTourTree(Action(apply: (d, x, n) => x + d * n), a: Some(vals)); et.link(0, 1); et.link(1, 2); et.cut(1, 2); not et.connected(0, 2)`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2449)

### `LazyEulerTourTree.connected`

```cp
fn connected(mut self, a: V, b: V) -> Bool
```

Whether `a` and `b` are in one tree.

- **cost**: expected O(log n)
- **traps**: never

Examples:

- `domain V = 0..4; let vals: [V]Int = [1, 2, 3, 4]; var et = LazyEulerTourTree(Action(apply: (d, x, n) => x + d * n), a: Some(vals)); et.link(0, 1); et.link(1, 2); not et.connected(0, 3)`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2456)

### `LazyEulerTourTree.len`

```cp
fn len(mut self, v: V) -> Int
```

The number of vertices in `v`'s tree.

- **cost**: expected O(log n)
- **traps**: never

Examples:

- `domain V = 0..4; let vals: [V]Int = [1, 2, 3, 4]; var et = LazyEulerTourTree(Action(apply: (d, x, n) => x + d * n), a: Some(vals)); et.link(0, 1); et.link(1, 2); et.len(1) == 3`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2463)

### `LazyEulerTourTree.get`

```cp
fn get(mut self, v: V) -> T
```

The value at `v`, with every update to a tree or side holding it applied.

- **cost**: expected O(log n)
- **traps**: never

Examples:

- `domain V = 0..4; let vals: [V]Int = [1, 2, 3, 4]; var et = LazyEulerTourTree(Action(apply: (d, x, n) => x + d * n), a: Some(vals)); et.link(0, 1); et.link(1, 2); et.apply_tree(0, 10); et.get(2) == 13 and et.get(3) == 4`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2470)

### `LazyEulerTourTree.set`

```cp
fn set(mut self, v: V, x: T)
```

Replaces the value at `v`, discarding earlier updates there.

- **cost**: expected O(log n)
- **traps**: never

Examples:

- `domain V = 0..4; let vals: [V]Int = [1, 2, 3, 4]; var et = LazyEulerTourTree(Action(apply: (d, x, n) => x + d * n), a: Some(vals)); et.link(0, 1); et.link(1, 2); et.set(0, 10); et.fold_tree(2) == 15`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2477)

### `LazyEulerTourTree.fold_tree`

```cp
fn fold_tree(mut self, v: V) -> T
```

The fold of every value in `v`'s tree.

- **cost**: expected O(log n)
- **traps**: never

Examples:

- `domain V = 0..4; let vals: [V]Int = [1, 2, 3, 4]; var et = LazyEulerTourTree(Action(apply: (d, x, n) => x + d * n), a: Some(vals)); et.link(0, 1); et.link(1, 2); et.fold_tree(0) == 6`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2484)

### `LazyEulerTourTree.fold_sub`

```cp
fn fold_sub(mut self, v: V, away: V) -> T
```

The fold over `v`'s side of the edge `v`-`away`.

- **cost**: expected O(log n)
- **traps**: when there is no edge `v`-`away`

Examples:

- `domain V = 0..4; let vals: [V]Int = [1, 2, 3, 4]; var et = LazyEulerTourTree(Action(apply: (d, x, n) => x + d * n), a: Some(vals)); et.link(0, 1); et.link(1, 2); et.fold_sub(1, 2) == 3`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2491)

### `LazyEulerTourTree.apply_tree`

```cp
fn apply_tree(mut self, v: V, f: F)
```

Applies `f` to every value in `v`'s tree.

- **cost**: expected O(log n)
- **traps**: never

Examples:

- `domain V = 0..4; let vals: [V]Int = [1, 2, 3, 4]; var et = LazyEulerTourTree(Action(apply: (d, x, n) => x + d * n), a: Some(vals)); et.link(0, 1); et.link(1, 2); et.apply_tree(0, 10); et.fold_tree(2) == 36 and et.get(3) == 4`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2498)

### `LazyEulerTourTree.apply_sub`

```cp
fn apply_sub(mut self, v: V, away: V, f: F)
```

Applies `f` to every value on `v`'s side of the edge `v`-`away`.

- **cost**: expected O(log n)
- **traps**: when there is no edge `v`-`away`

Examples:

- `domain V = 0..4; let vals: [V]Int = [1, 2, 3, 4]; var et = LazyEulerTourTree(Action(apply: (d, x, n) => x + d * n), a: Some(vals)); et.link(0, 1); et.link(1, 2); et.apply_sub(1, 2, 10); et.get(0) == 11 and et.get(2) == 3 and et.fold_tree(0) == 26`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2505)

## `KruskalTree`

```cp
pub struct KruskalTree
```

The Kruskal reconstruction tree: each edge that merges two components, in increasing
weight, becomes a node above them. The leaves under a node are the vertices connected by
edges of weight at most its own, so "what `v` reaches under a limit" is one subtree.

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2523)

### `KruskalTree.leaf`

```cp
leaf: [V]N
```

The leaf node of each vertex.

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2525)

### `KruskalTree.w`

```cp
w: [N]?W
```

The merging weight of each node; `None` at a leaf.

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2527)

### `KruskalTree.tree`

```cp
fn tree(self) -> Rooted
```

The nodes as a `Rooted` forest over `N`: subtree ranges, LCA and folds. The roots, one per
component, are in increasing node order.

- **cost**: O(1); built with the tree
- **traps**: never

Examples:

- `domain V = 0..3; let es: [0..2](u: V, v: V, w: Int) = [(u: 0, v: 1, w: 5), (u: 1, v: 2, w: 3)]; let (domain N, kt) = kruskal_tree(es, w: e => es[e].w); kt.tree.parent(kt.leaf[1]) == kt.tree.parent(kt.leaf[2]) and kt.tree.size(kt.leaf[0]) == 1`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2536)

### `KruskalTree.reach`

```cp
fn reach(self, v: V, limit: W) -> N
```

The highest node above `leaf[v]` whose weight is at most `limit` (`leaf[v]` itself when
None is); its leaves are what `v` reaches by edges of weight at most `limit`.

- **cost**: O(log n)
- **traps**: never

Examples:

- `domain V = 0..3; let es: [0..2](u: V, v: V, w: Int) = [(u: 0, v: 1, w: 5), (u: 1, v: 2, w: 3)]; let (domain N, kt) = kruskal_tree(es, w: e => es[e].w); kt.reach(0, 4) == kt.leaf[0] and kt.w[kt.reach(1, 4)] == Some(3) and kt.w[kt.reach(1, 5)] == Some(5)`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2544)

### `KruskalTree.top`

```cp
fn top(self, v: V, ok: E -> Bool) -> N
```

The highest node above `leaf[v]` whose merging edge, and every one below it, satisfies `ok`,
which gets the edge's key in the list given to `kruskal_tree`
(`kt.top(v, ok: e => roads[e].alt > p)`). `ok` must hold on a prefix of the merge order.

- **cost**: O(log n) calls of `ok`
- **ties**: None; the highest such node is unique
- **traps**: never

Examples:

- `domain V = 0..3; let es: [0..2](u: V, v: V, w: Int) = [(u: 0, v: 1, w: 5), (u: 1, v: 2, w: 3)]; let (domain N, kt) = kruskal_tree(es, w: e => es[e].w); kt.w[kt.top(1, e => es[e].w < 5)] == Some(3) and kt.top(0, e => false) == kt.leaf[0]`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2554)

### `KruskalTree.up`

```cp
fn up(self, op: M, leaf: V -> T) -> [N]T
```

For every node, `op` folded over the `leaf` values of the leaves under it, in vertex order:
the least walk home from any vertex a subtree reaches is `kt.up(min, leaf: v => home[v]!)`.

- **cost**: O(n) calls of `op` and `leaf`
- **empty**: never empty; every leaf has a value
- **order**: keyed by `N`
- **traps**: never

Examples:

- `domain V = 0..3; let es: [0..2](u: V, v: V, w: Int) = [(u: 0, v: 1, w: 5), (u: 1, v: 2, w: 3)]; let (domain N, kt) = kruskal_tree(es, w: e => es[e].w); let c = kt.up(add, leaf: v => 1); c[kt.reach(2, 3)] == 2 and c[kt.leaf[0]] == 1`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2564)

### `KruskalTree.bottleneck`

```cp
fn bottleneck(self, a: V, b: V) -> ?W
```

The least possible largest edge weight on a path from `a` to `b`: the weight of their
lowest common ancestor. `None` when they are not connected, and at `a == b`.

- **cost**: O(log n)
- **traps**: never

Examples:

- `domain V = 0..3; let es: [0..2](u: V, v: V, w: Int) = [(u: 0, v: 1, w: 5), (u: 1, v: 2, w: 3)]; let (domain N, kt) = kruskal_tree(es, w: e => es[e].w); kt.bottleneck(0, 2) == Some(5) and kt.bottleneck(1, 2) == Some(3) and kt.bottleneck(0, 0) == None`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/tree.cp#L2572)

---

# window

URL: /docs/ref/std/window

Generated from [spec/std/window.cp](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/window.cp) by `cpl doc --format json`.



## `Window`

```cp
pub struct Window(op: M)
```

A sliding fold queue over `op`. `push` and `pop` are O(1) amortized; `all` is O(1).

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/window.cp#L12)

### `Window.new`

```cp
fn new(op: M) -> Window
```

An empty window over `op`. The strategy comes from `op`'s laws: a `Group` keeps a running
total and subtracts on `pop`, a `Selective` op (`min`, `max`, `min(by:)`) keeps a monotone
deque, and anything else keeps two stacks.

- **cost**: O(1)
- **traps**: never

Examples:

- `var w = Window(+); w.all == None`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/window.cp#L24)

### `Window.push`

```cp
fn push(mut self, x: T)
```

Push `x` at the back, as the newest element.

- **cost**: O(1) amortized calls of `op`
- **traps**: never (beyond what `op` traps on)

Examples:

- `var w = Window(max); w.push(3); w.push(5); w.all == Some(5)`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/window.cp#L32)

### `Window.pop`

```cp
fn pop(mut self)
```

Pop the front: remove the oldest element.

- **cost**: O(1) amortized calls of `op`
- **traps**: on an empty window

Examples:

- `var w = Window(min); w.push(3); w.push(1); w.push(2); w.pop(); w.all == Some(1)`
- `var w = Window(min); w.push(1); w.push(2); w.pop(); w.all == Some(2)`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/window.cp#L41)

### `Window.all`

```cp
fn all(self) -> ?T
```

The fold of the current contents, oldest first (`op(op(x1, x2), x3)` for pushes `x1`, `x2`,
`x3`), so a non-commutative op folds in push order; `None` when empty.

- **cost**: O(1)
- **empty**: `None`
- **traps**: never

Examples:

- `var w = Window(+); w.push(2); w.push(3); w.all == Some(5)`
- `var w = Window(+); w.push(2); w.pop(); w.all == None`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/window.cp#L52)

### `Window.len`

```cp
fn len(self) -> Int
```

The number of elements in the window: pushes minus pops.

- **cost**: O(1)
- **traps**: never

Examples:

- `var w = Window(+); w.push(2); w.push(3); w.pop(); w.len == 1`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/window.cp#L63)

### `Window.push_back`

```cp
fn push_back(mut self, x: T)
```

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/window.cp#L66)

### `Window.drop_front`

```cp
fn drop_front(mut self)
```

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/window.cp#L71)

## `Track`

```cp
pub trait Track
```

State a window can add to at the back and remove from at the front. `pop(x)` is passed the
element leaving the front. `Window(op)`, `Counter`, `Tracked` and `Undoing` implement it.

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/window.cp#L87)

### `Track.push`

```cp
fn push(mut self, x: T)
```

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/window.cp#L88)

### `Track.pop`

```cp
fn pop(mut self, x: T)
```

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/window.cp#L89)

## `Counter`

```cp
impl Track for Counter
```

`push(x)` adds 1 to `x`'s count and `pop(x)` takes 1 away, so `len` is the number of distinct
values in the window.

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/window.cp#L93)

### `Counter.push`

```cp
fn push(mut self, x: K)
```

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/window.cp#L94)

### `Counter.pop`

```cp
fn pop(mut self, x: K)
```

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/window.cp#L96)

## `Window`

```cp
impl Track for Window
```

`push(x)` is `Window.push(x)`; `pop(x)` is `Window.pop()`, which already knows the front.

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/window.cp#L100)

### `Window.push`

```cp
fn push(mut self, x: T)
```

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/window.cp#L101)

### `Window.pop`

```cp
fn pop(mut self, x: T)
```

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/window.cp#L103)

## `Tracked`

```cp
pub struct Tracked(state: S, add: (mut S, T) -> (), remove: (mut S, T) -> ())
```

A `Track` built from a structure and two closures.

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/window.cp#L119)

### `Tracked.push`

```cp
fn push(mut self, x: T)
```

Apply `x` at the back: one call of `add(state, x)`.

- **cost**: one call of `add`
- **traps**: never (beyond what `add` traps on)

Examples:

- `var t = track(0, (mut s, x) => s += x, (mut s, x) => s -= x); t.push(3); t.state == 3`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/window.cp#L125)

### `Tracked.pop`

```cp
fn pop(mut self, x: T)
```

Take the front element `x` back out: one call of `remove(state, x)`. `x` is passed through
as given; nothing checks that it is the oldest element.

- **cost**: one call of `remove`
- **traps**: never (beyond what `remove` traps on)

Examples:

- `var t = track(0, (mut s, x) => s += x, (mut s, x) => s -= x); t.push(3); t.push(4); t.pop(3); t.state == 4`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/window.cp#L133)

### `Tracked.state`

```cp
fn state(self) -> S
```

The structure with exactly the window's elements applied.

- **cost**: O(1)
- **traps**: never

Examples:

- `track(7, (mut s, x) => s += x, (mut s, x) => s -= x).state == 7`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/window.cp#L141)

## `Undo`

```cp
pub trait Undo
```

A structure that can return to an earlier state, newest change first: `Dsu`, `ParityDsu`,
`WeightedDsu`, `DsuWith`, `RollbackArray`, and any user struct with these two methods.

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/window.cp#L145)

### `Undo.mark`

```cp
fn mark(mut self) -> Mark
```

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/window.cp#L146)

### `Undo.undo_to`

```cp
fn undo_to(mut self, snap: Mark)
```

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/window.cp#L147)

## `Dsu`

```cp
impl Undo for Dsu
```

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/window.cp#L149)

### `Dsu.mark`

```cp
fn mark(mut self) -> Mark
```

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/window.cp#L150)

### `Dsu.undo_to`

```cp
fn undo_to(mut self, snap: Mark)
```

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/window.cp#L151)

## `DsuOf`

```cp
impl Undo for DsuOf
```

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/window.cp#L153)

### `DsuOf.mark`

```cp
fn mark(mut self) -> Mark
```

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/window.cp#L154)

### `DsuOf.undo_to`

```cp
fn undo_to(mut self, snap: Mark)
```

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/window.cp#L155)

## `ParityDsu`

```cp
impl Undo for ParityDsu
```

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/window.cp#L157)

### `ParityDsu.mark`

```cp
fn mark(mut self) -> Mark
```

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/window.cp#L158)

### `ParityDsu.undo_to`

```cp
fn undo_to(mut self, snap: Mark)
```

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/window.cp#L159)

## `PotentialDsu`

```cp
impl Undo for PotentialDsu
```

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/window.cp#L161)

### `PotentialDsu.mark`

```cp
fn mark(mut self) -> Mark
```

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/window.cp#L162)

### `PotentialDsu.undo_to`

```cp
fn undo_to(mut self, snap: Mark)
```

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/window.cp#L163)

## `Undoing`

```cp
pub struct Undoing(state: S, add: (mut S, T) -> ())
```

The queue-undo trick: a `Track` over an `Undo` structure, so a window that adds at the back
and drops from the front runs on a structure that can only undo its newest change (a
rollback DSU in a two-pointer pass). `add(mut state, x)` applies one element; `state`
always holds exactly the window's elements. Each element is applied O(log n) times
amortized, so a pass of n pushes and pops costs O(n log n) applications.

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/window.cp#L170)

### `Undoing.push_entry`

```cp
fn push_entry(mut self, x: T, b: Bool)
```

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/window.cp#L176)

### `Undoing.push`

```cp
fn push(mut self, x: T)
```

Push `x` at the back: one `add` on top of the current state.

- **cost**: O(1) applications of `add` amortized
- **traps**: never (beyond what `add` traps on)

Examples:

- `domain V = 0..3; var u = undoing(Dsu(rollback: true), (mut d, e) => d.unite(e.0, e.1)); u.push((V(0), V(1))); u.state.same(V(0), V(1))`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/window.cp#L188)

### `Undoing.pop`

```cp
fn pop(mut self, x: T)
```

Drop the front element, which must be `x`. The element removed is the stored oldest one;
`x` names it for the `Track` protocol and is not compared. Undoes back past the oldest
change and re-applies the rest (the queue-undo trick).

- **cost**: O(log n) applications of `add` amortized
- **traps**: on an empty `Undoing`

Examples:

- `domain V = 0..3; var u = undoing(Dsu(rollback: true), (mut d, e) => d.unite(e.0, e.1)); u.push((V(0), V(1))); u.push((V(1), V(2))); u.pop((V(0), V(1))); u.state.same(V(1), V(2)) and not u.state.same(V(0), V(1))`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/window.cp#L198)

### `Undoing.state`

```cp
fn state(self) -> S
```

The structure with exactly the window's elements applied.

- **cost**: O(1)
- **traps**: never

Examples:

- `domain V = 0..3; let u = undoing(Dsu(rollback: true), (mut d, e) => d.unite(e.0, e.1)); not u.state.same(V(0), V(1))`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/window.cp#L243)

## `Sweep`

```cp
pub struct Sweep(state: S)
```

A movable interval over `D` feeding a `Track`, for Mo and divide-and-conquer DP. Moving
expands before shrinking. O(|change|) pushes and pops per move.

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/window.cp#L255)

### `Sweep.new`

```cp
fn new(state: S, start: ?Range = None) -> Sweep
```

A sweep over `state`, starting empty (or at `start`). Empty means the range is empty at the
first cut of `D`; with `start`, each position of `start` is pushed in increasing order.

- **cost**: O(1), plus `start.len` pushes when `start` is given
- **empty**: an empty `start` is the same as None, but sits at `start`'s cut
- **traps**: never (beyond what `state.push` traps on)

Examples:

- `domain D = 0..5; let s = Sweep>(Counter(0)); s.range.len == 0`
- `domain D = 0..5; let s = Sweep>(Counter(0), start: Some(1..3)); s.range == 1..3`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/window.cp#L267)

### `Sweep.move`

```cp
fn move(mut self, to: Range)
```

Slide to `to`, feeding `state` the positions that enter and leave. Moving expands before
shrinking, in this order: grow the right end (push each new position, increasing), grow the
left end (push, decreasing), shrink the right end (pop, decreasing), shrink the left end
(pop, increasing). The state never sees a negative-length interval, but growing on the left
and shrinking on the right touch the "wrong" end of the `Track`, so as with Mo the state's
answer must ignore order.

- **cost**: O(|dl| + |dr|) pushes and pops, where `dl` and `dr` are the moves of the two ends
- **empty**: moving to an empty `to` pops everything
- **traps**: never (beyond what the state traps on)

Examples:

- `domain D = 0..5; var s = Sweep>(Counter(0)); s.move(1..4); s.move(2..5); s.range == 2..5`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/window.cp#L283)

### `Sweep.range`

```cp
fn range(self) -> Range
```

The current interval: the positions whose pushes the state holds.

- **cost**: O(1)
- **traps**: never
- **order**: increasing positions of `D`

Examples:

- `domain D = 0..5; var s = Sweep>(Counter(0)); s.move(0..2); s.range.len == 2`

[Source](https://github.com/ryanbai1412/cp-lang/blob/main/spec/std/window.cp#L308)

---

# Bundling and submission

URL: /docs/ref/tools/bundle

Normative text from [spec/tools/bundle.md](https://github.com/ryanbai1412/cp-lang/blob/main/spec/tools/bundle.md).


Status: draft for 0.3.0. Sources: `plan/40-tooling.md` §4-5,
`plan/70-judges.md` §7.3, decision 31.

- `cpl build` emits one deterministic C++17 file for the judge profile:
  the stamp and source hash, the used runtime pieces, the reached
  library instances (tree-shaken), the program, `main`.
- Stripped: tests, alts, generators, checkers, interactors, samples,
  `debug(...)`, `@local` items.
- Libraries are inlined from the content-addressed store by pin, so a
  rebuild is byte-identical; `cpl vendor` copies them next to the file.
- Size is checked against the profile; `--size` attributes bytes to
  header, runtime, types, library functions, user code and glue.
- `@cpp("...", includes:)` items and `extern fn` judge functions are
  emitted verbatim or as declarations.

---

# The cpl command

URL: /docs/ref/tools/cli

Normative text from [spec/tools/cli.md](https://github.com/ryanbai1412/cp-lang/blob/main/spec/tools/cli.md).


Status: draft for 0.3.0. Sources: `plan/40-tooling.md` §8, decisions 34,
36. Every command takes a file (`d`, `d.cp`, a path) and defaults to the
most recently edited `.cp` file in the folder.

| Command | Does |
|---|---|
| `cpl new d` | creates `d.cp` from the template and `d.tests/` |
| `cpl fetch ` | downloads samples into `d.tests/` |
| `cpl run d [files]` | checked build in the interpreter, on files or stdin; compares with `.out` files if present; `--release` runs the judge's C++ |
| `cpl test d` | every case in `d.tests/`, inline `@sample`s and `@test` fns |
| `cpl stress d` | alternatives, generators, checkers, law sampling; shrinks and saves failures (`tools/stress.md`) |
| `cpl locate d` | the smallest failing input and the first part whose alt disagrees |
| `cpl interact d` | runs against an `@interactor` or an external interactor binary |
| `cpl explain d [name]` | layouts, widths, niches, peak memory, specializations, checks, copies (`tools/explain.md`) |
| `cpl trace d input` | HTML trace of a run (`tools/trace-debug.md`) |
| `cpl debug d input` | the debugger over the interpreter |
| `cpl profile d input` | per-line time and allocation on the release C++ |
| `cpl cover d` | which lines and branches the tests reach |
| `cpl bench d` | release runtime against the profile's limits and against a matched C++ file if given |
| `cpl fmt [files]` | canonical formatting (`tools/fmt-lint.md`) |
| `cpl lint [files]` | lints with autofixes |
| `cpl build d` | the C++ for the file's judge; `--checked`, `--size`, `--judge`, `--copy` |
| `cpl submit d` | `build`, then the cases on that build with the judge's flags; `--copy` puts the file on the clipboard |
| `cpl migrate` | runs codemods to a new stdlib version and updates pins |
| `cpl judges` | lists judge profiles |
| `cpl doc` | renders library docs from doc comments |
| `cpl lsp` | the language server |
| `cpl watch d` | rebuild and test on save |
| `cpl selftest` | interpreter and C++ agreement on the corpus |

Output is plain text for people and `--json` for tools; exit codes are
0 success, 1 failure of the program or a test, 2 compile error, 3 usage
error. Everything is deterministic given the seed.

---

# cpl explain

URL: /docs/ref/tools/explain

Normative text from [spec/tools/explain.md](https://github.com/ryanbai1412/cp-lang/blob/main/spec/tools/explain.md).


Status: draft for 0.3.0. The report every implicit choice owes the
contestant (AGENTS.md "nothing secret under the hood"). Its content is
defined by `core/13-lowering.md` §13.6; the LSP shows the same data.

```
$ cpl explain d dist
dist: [V]?Int
  element  8 B, None = Int.MIN
  count    V.count <= 2e5   peak 1.6 MB
$ cpl explain d Ev
Ev  8 B  (Ask: l @0 4 B, r @4 4 B; Add: v @0, r = 0xFFFFFFFF)
?Ev 8 B  None = r 0xFFFFFFFE
$ cpl explain d st
st: SegTree(max, a, act: add)   iterative, no push-down (add commutes)
  nodes 4 B x 2^19 = 2 MB       (max is Selective over 1..=1e9)
```

Sections: types (size, storage order, padding, niches), arrays (width,
peak bytes, `wide_array` and padding notes with fixes), memory total
against the profile, specializations and the laws or bounds that chose
them, remaining checks per build, contexts and generic instances with
output bytes, unsafe-tier sites. `--json` for tools.

---

# Formatter and linter

URL: /docs/ref/tools/fmt-lint

Normative text from [spec/tools/fmt-lint.md](https://github.com/ryanbai1412/cp-lang/blob/main/spec/tools/fmt-lint.md).


Status: draft for 0.3.0. Sources: `plan/45-dev-tools.md`, decisions 70,
93, 140, 144, 148.

## `cpl fmt`

One canonical layout, no options: 4-space indents, 100 columns,
`with` lines first in their block, sorted `use` lines, one blank line
between items, trailing commas in multi-line brackets, the compiler
stamp on line 1. Formatting never changes meaning; it is idempotent and
fast enough to run on every save.

## `cpl lint`

Lints flag legal code that is probably wrong, slow or unidiomatic. They
never block a build. Each has a stable code, a default level, a message
that says what to write instead, and an autofix where possible. A lint
is declared by the library that owns the names it mentions; the linter
has no hard-coded stdlib names. Levels are set in `cp.toml [lints]` or
in code with `with lint(name: allow)`.

The 0.3 set is catalogued in `../diagnostics.md` (codes `L....`),
including: same-place read and write in one statement
(`a[l] += inc(mut a[l])`, `xs[0] = xs.pop()!`); a lazy chain walked
twice or a `.map` recomputed per read; a generator holding a `mut`
lend walked twice; a literal index into a slice (`w[0]`); a domain-
keyed `Map`; `==` on floats; `wide_array`; padding over 20 %; a `var`
never reassigned; an unused result; a `@memo(array)` over the memory
budget; a shadowed top-level `let`.

---

# Judge profiles

URL: /docs/ref/tools/judge-profiles

Normative text from [spec/tools/judge-profiles.md](https://github.com/ryanbai1412/cp-lang/blob/main/spec/tools/judge-profiles.md).


Status: draft for 0.3.0. Sources: `plan/70-judges.md`, decisions 31, 34,
148. Implemented in `crates/cpl-judge`.

A profile fixes everything that differs between judges: compiler and
flags, OS, the judge's stack and the program thread's stack, source
size limit, `__int128` availability, time and memory limits, `answers`
and `precision` defaults for `io`, instruction set, and which checks
stay in release.

- Built in: `generic` (default), `codeforces`, `atcoder`, `cses`,
  `icpc`, `kattis`, `dmoj`, `usaco`; `ioi` (grader-style) is proposed.
- Chosen by `--judge`, else a `// judge: name` line, else `cp.toml`.
  `[judge.]` tables override fields or `extends` a profile.

```text
[judge.school]
extends = "icpc"
stack_mb = 64
thread_stack_mb = 512        # 0 if the judge bans threads
source_kb = 100
flags = ["-std=c++17", "-O2"]
int128 = false
time_ms = 2000
memory_mb = 256
release_checks = []          # e.g. ["ranges", "overflow", "reads"]
isa = "x86-64"               # later: "avx2" enables target pragmas
answers = ["YES", "NO"]
```

- `I128` on a profile without `__int128` is an error naming the judge.
- Size: a warning above 32 KB (or half of a smaller `source_kb`), an
  error above 64 KB or `source_kb`, whichever is smaller; `--size`
  breaks the file down by part.
- `time_ms` and `memory_mb` are a problem's limits when its `cp.toml`
  has no `[limits]`.
- `memory_mb` feeds `cpl explain`'s peak-memory check and the LSP's
  code lens; `time_ms` feeds `cpl bench`.
- Local release runs build with the profile's flags and run under its
  stack (`ulimit -s`), so judge-only crashes reproduce locally.

---

# Language server and editors

URL: /docs/ref/tools/lsp

Normative text from [spec/tools/lsp.md](https://github.com/ryanbai1412/cp-lang/blob/main/spec/tools/lsp.md).


Status: draft for 0.3.0. Sources: `plan/60-editor.md`, decisions 29,
149. One compiler serves `cpl` and the LSP.

- **Diagnostics** as you type, cheapest first (syntax, names, types,
  domains, borrows, ranges); one error per root cause; each with its
  code, an index link and fixes as code actions. Cost and overflow
  warnings show the estimate on hover.
- **Hover**: the type, where `None` lives, storage width and peak bytes,
  proven ranges, the cost of a call, and representation choices
  (niche, width from a range, specialization chosen by a law).
- **Storage sizes** (decision 149): hover on a type or variable gives its
  size, field storage order, padding and niche; inlay hints after array
  and structure declarations give element size and peak bytes at the
  input bounds (`var dist: [V]?Int  // 8 B x 2e5 = 1.6 MB`); a code lens
  above the program shows total peak memory against the judge profile;
  padding over 20 % and `wide_array` are quick fixes. The numbers come
  from the same computation as `cpl explain`.
- **Inlay hints**: inferred types, parameter names past two positional
  arguments, opt-in live sample values per top-level `let`.
- **Completion** ranked by type (positions of `V` inside `a[` for
  `a: [V]T`, operation values where an `Op` is expected, unimported
  stdlib names with the `use` edit); signature help with bound
  explanations.
- **Navigation and refactoring**: definition, references, rename,
  extract nested fn, inline, add dimension to a DP table, convert array
  to map.
- **Editors**: a VS Code extension (highlighting, run/test/stress
  buttons, debugger, trace panel, judge in the status bar); any LSP
  client works for the rest.

---

# Stress, shrinking and laws

URL: /docs/ref/tools/stress

Normative text from [spec/tools/stress.md](https://github.com/ryanbai1412/cp-lang/blob/main/spec/tools/stress.md).


Status: draft for 0.3.0. The library side is `lib/random-stress.md`.

`cpl stress d` builds the checked program, finds every `@alt`, `@gen`,
`@check` and `@interactor`, and runs rounds:

1. Generate an input from `@gen` or from the program's reads.
2. Run the program and each applicable alt (whole-program alts compare
   output; inner alts are substituted at call sites and compared there).
3. Apply the relation and unary checkers; sample laws of operation
   values the run built; for `@cache` fields, rerun with caches cold and
   compare.
4. On failure, shrink the recorded `gen` choices to a minimal input that
   still fails, then report it, each implementation's output, the first
   differing line, and the first part whose alt disagrees, with values in
   the file's base. Save it to `d.tests/stress-.in`.

Options: `--time`, `--threads`, `--seed`, `--max-size`, `--laws=off`.
Runs are deterministic per seed and parallel across threads. `cpl
locate` is stress plus part-level bisection on a given failing input.

---

# Traces, the debugger and runtime errors

URL: /docs/ref/tools/trace-debug

Normative text from [spec/tools/trace-debug.md](https://github.com/ryanbai1412/cp-lang/blob/main/spec/tools/trace-debug.md).


Status: draft for 0.3.0. Sources: `plan/50-debugging.md`, decisions 41,
43.

- **Traps** (checked builds) print the rule, the place and local values
  in source terms (positions in the file's base, ranges by name), plus
  the call trace. Output written so far is flushed first.
- **`cpl trace d input`** writes one HTML file: every top-level
  statement and part call with its inputs and result, each read token
  with the value it became and the line that consumed it, and
  collapsible loops. Quiet by default: no per-iteration rows unless a
  filter asks (`--at line`, `--var name`, `--when expr`).
- **Stage snapshots**: `cpl snap` saves a part's inputs; `cpl run d
  --stage snap` reruns only that part while iterating.
- **`debug(x)`** prints with a source location in checked builds and is
  removed from submissions.
- **The debugger** (`cpl debug`, DAP for editors) runs on the
  interpreter: breakpoints, conditional breakpoints, step into
  generators and closures, watch expressions in the language, and
  reverse step over the recorded run.
- Interpreter and C++ agree on every program, including on input they
  reject; `cpl selftest` checks it.

---

# Release notes

URL: /docs/releases

{/* Generated by scripts/releases.mjs from CHANGELOG.md; edit that file instead. */}

## 0.3.0 (unreleased)

The 0.3.0 language is specified but not yet implemented. Its normative
source is `spec/`; `spec/STATUS.md` says how far the work has got.

### Language

- Enum variants are PascalCase: `Some`, `None`, `Anchor.Start`. In a
  pattern, a capitalised name is a variant and a lowercase name binds
  (decision 157).
- Memoized functions use `@cache` instead of `@memo`.
- Decorators go before `pub`: `@get pub fn`.
- `-\> lends T` always has the arrow.

### Library

- The library is respecified in `spec/std/`: about 1,700 documented
  signatures, each with its cost. Bodies are `todo` until the library is
  built.
- Prefix sums and Fenwick trees answer range queries with `fold(r)`, not
  `sum`.
- Substring search is `s.search(p)` and `s.rsearch(p)`; `find` and `rfind`
  take predicates only.
- `collect()` and `sorted()` return a `List` keyed from 0.
- New general mechanisms found by porting 100 real problems: `buckets`,
  `read_all`, `pieces`, `closure` and `try_from_parents` (decisions 158 to
  165).

### Breaking changes

- `none` becomes `None` and `some` becomes `Some`. The 0.2.2 compiler
  already accepts both spellings.
- `@memo` becomes `@cache`.

## 0.2.2 (2026-11-20)

The first numbered release of the language and its toolchain.

### Tools

- `cpl`: `check`, `fix`, `run` (the debug interpreter), `build` (one C++17
  file to submit), `fmt`, `lint`, `explain` and `doc`.
- Contest workflow: `new`, `test`, `watch`, `bench`, `stress` (against a
  brute, shrinking the failing case), `profile`, `cover` and `submit`.
- Judge profiles for generic C++17, Codeforces, AtCoder, CSES, ICPC and
  more, selected per file or project (`cpl judges`).
- `cpl lsp` for every editor, with support for VS Code, Neovim, Helix, Zed,
  Emacs and JetBrains IDEs in `editors/`; `cpl dap` for time-travel
  debugging.
- A WASM build of the compiler that runs in the browser.