ADS
Algorithms and Data Structures
Loading...
Searching...
No Matches
Theory of the foundations

The headers of include/ADS itself hold what the other areas take for granted: the abstract data types of chapters 3 and 4 of the book as concepts of C++20 (ADT.h), the preconditions, the postconditions and the invariants that the operations check at run time (Contract.h), the iterators that the containers share (Iterators.h), and the primitives of the processor in one portable form (Portable.h). This page collects the definitions behind them, i.e., what a specification of an abstract data type is and what its axioms say (see Definitions and notation and Abstract data types and their axioms), what a contract is and why each kind of contract is checked at its own level (see Contracts), and the categories of the iterators with the cost of their steps (see Iterators), while the arithmetic of the portable primitives (see Portable primitives) and the typed modifications by which a structure tells its observers what changed (see Typed modifications) and the capabilities that an algorithm may ask of a structure (see Capabilities), and the algebra by which an aggregate chooses its update rule (see The algebra of the aggregates) close the page. The algorithms of the iterators have their pseudocode on the page of Iterators.h, in the comment of their function.

Definitions and notation

A specification of an abstract data type is a triple \( ( D , F , A ) \) (section 3.2 of the book): \( D \) is a set of domains, one of which is the designated domain, i.e., the type being defined (e.g., the stacks), and the others are the auxiliary ones (e.g., the items and the booleans); \( F \) is a set of operations, each a function among the domains of \( D \); \( A \) is a set of axioms, which give the semantics of \( F \). The pair \( ( D , F ) \) is the syntactic specification, which a concept of C++20 states as the names of the operations and the types of their arguments and results, and \( A \) is the semantic one, which no compiler checks. The semantics may be given in two ways: (i) algebraic, by equations among the operations, those that observe or remove written on those that construct, as in \( \mathrm{top}( \mathrm{push}( S , v ) ) = v \); (ii) constructive, by the precondition and the postcondition of each operation, written in terms of a type already known (e.g., the finite sequences of items). The library states (i) in the comments of ADT.h and checks (ii) in the code, by the macros of Contract.h, and its tests check both on every realization.

The operations are of four kinds: the constructors, which make a value of the type (create(), insert(), push()); the modifiers, which change it; the observers, which return a property of it (empty(), top(), read()); the iterators, which visit its items. A realization meets the requirement of abstraction, i.e., a program that uses the type does not depend on how it is realized, and that of protection, i.e., only the operations of the type act on its values; hence each realization is a class whose data are private, and one realization can replace another under the same concept (Liskov and Zilles, Parnas).

The symbols of the headers of the area
SymbolMeaning
\( ( D , F , A ) \)a specification: the domains, the operations and the axioms
\( s_0 , \ldots , s_{n-1} \)the items of a SEQUENCE of length \( n \), \( s_i \) the item of index \( i \)
\( \mathit{pos}_i \)the position of \( s_i \), of the type Pos of the realization, for \( 0 \le i < n \); \( \mathit{pos}_{-1} \) and \( \mathit{pos}_n \) are the positions before the first item and after the last one, on which finished() is true
\( \{ P \}\ \mathit{op}\ \{ Q \} \)a contract: if the precondition \( P \) holds when the operation \( \mathit{op} \) starts, the postcondition \( Q \) holds when it ends
\( I \)the invariant of a structure, a property of its representation that holds between any two of its operations
\( h \)the height of a binary tree, the length of its longest path from the root
\( c \), \( m \)the capacity of a circular vector, and the number of places of a table

Abstract data types and their axioms

The concepts of ADT.h are the five abstract data types of chapters 3 and 4 of the book, and the headers of the areas realize them, each in several ways; the concepts state the syntactic specification, so that a function template written on Stack takes any of the stacks of include/ADS/stack, and the axioms below are their semantics.

The concepts of ADT.h, their operations and the areas that realize them
ConceptAbstract typeOperationsSection of the bookArea
SequenceSEQUENCEempty(), finished(), head(), tail(), next(), prev(), insert(), remove(), read(), write()3.2.1include/ADS/sequence
SetSETsize(), contains(), insert(), remove()3.2.2include/ADS/set
DictionaryDICTIONARYlookup(), insert(), remove()3.2.3include/ADS/dictionary
StackSTACKempty(), push(), pop(), top()4.3.1include/ADS/stack
QueueQUEUEempty(), enqueue(), dequeue(), top()4.3.1include/ADS/queue

The axioms of the STACK, with \( \mathrm{create} \) the empty stack, are

\[ \begin{array}{ll} \mathrm{empty}( \mathrm{create} ) = \mathbf{true} , & \mathrm{empty}( \mathrm{push}( S , v ) ) = \mathbf{false} , \cr \mathrm{top}( \mathrm{push}( S , v ) ) = v , & \mathrm{pop}( \mathrm{push}( S , v ) ) = S , \end{array} \tag{1} \]

while \( \mathrm{top}( \mathrm{create} ) \) and \( \mathrm{pop}( \mathrm{create} ) \) are undefined, i.e., top() and pop() are partial, with the precondition that the stack is not empty. Those of the QUEUE, for \( Q \) not empty, are

\[ \mathrm{top}( \mathrm{enqueue}( Q , v ) ) = \mathrm{top}( Q ) , \qquad \mathrm{dequeue}( \mathrm{enqueue}( Q , v ) ) = \mathrm{enqueue}( \mathrm{dequeue}( Q ) , v ) , \tag{2} \]

with \( \mathrm{empty}( \mathrm{create} ) = \mathbf{true} \), \( \mathrm{empty}( \mathrm{enqueue}( Q , v ) ) = \mathbf{false} \) for any \( Q \), \( \mathrm{top}( \mathrm{enqueue}( \mathrm{create} , v ) ) = v \) and \( \mathrm{dequeue}( \mathrm{enqueue}( \mathrm{create} , v ) ) = \mathrm{create} \); the difference between (1) and (2) is the whole difference between the two types, since their syntactic specifications are the same up to the names. Those of the SET and of the DICTIONARY define the observer on each constructor, e.g., for the SET

\[ \mathrm{contains}( x , \mathrm{insert}( y , A ) ) = ( x = y ) \lor \mathrm{contains}( x , A ) , \qquad \mathrm{contains}( x , \mathrm{remove}( y , A ) ) = ( x \ne y ) \land \mathrm{contains}( x , A ) , \tag{3} \]

with \( \mathrm{contains}( x , \mathrm{create} ) = \mathbf{false} \), so that inserting an item already there, or removing one that is not, leaves the set as it is (the library relaxes in this way the preconditions \( x \notin A \) and \( x \in A \) that some specifications state).

Lemma 1 (the normal form of the stacks). By (1), every stack built by \( \mathrm{create} \), \( \mathrm{push} \) and \( \mathrm{pop} \), each \( \mathrm{pop} \) applied to a stack not empty, is equal to a term

\[ \mathrm{push}( \cdots \mathrm{push}( \mathrm{push}( \mathrm{create} , v_1 ) , v_2 ) \cdots , v_k ) , \quad k \ge 0 , \tag{4} \]

and the observers of a term (4) are known: it is empty if and only if \( k = 0 \), and its top is \( v_k \).

Indeed, by induction on the number of operations of the term, a \( \mathrm{push} \) applied to a term (4) is a term (4), and a \( \mathrm{pop} \) applied to a term (4) with \( k \ge 1 \) is, by the last axiom of (1), the term (4) of \( v_1 , \ldots , v_{k-1} \). The axioms are therefore sufficiently complete: they decide the value of every observer on every stack, which is what makes them a specification rather than a list of properties (Guttag and Horning). The same holds for the queues by (2), the normal form being made of \( \mathrm{enqueue} \) alone (a \( \mathrm{dequeue} \) of a normal form of \( k \ge 1 \) items is, by induction on \( k \), the normal form of its last \( k - 1 \) items). For the sets, (3) decides \( \mathrm{contains}( x , A ) \) for every \( x \) and every term \( A \), by induction on \( A \); hence, if two sets are taken as equal when they contain the same items, every term is equal to a term made of \( \mathrm{insert} \) alone, on the distinct items that it contains, in any order.

The SEQUENCE is specified in the constructive way, by its positions. As in the book, \( \mathrm{insert}( p , v ) \) with \( p = \mathit{pos}_i \) puts \( v \) at the index \( i \), the old items from the index \( i \) moving one place on, and returns the position of the new item, while \( \mathrm{remove}( p ) \) with \( p = \mathit{pos}_i \) removes the item of index \( i \) and returns the position of the new item of index \( i \); hence the axioms

\[ \mathrm{read}( \mathrm{insert}( p , v ) ) = v , \qquad \mathrm{remove}( \mathrm{insert}( p , v ) ) = s , \qquad \mathrm{read}( \mathrm{write}( p , v ) ) = v , \tag{5} \]

the last with the other items unchanged, and \( \mathrm{empty}( s ) = \mathrm{finished}( \mathrm{head}( s ) ) \), which makes empty() redundant. What a position is depends on the realization (an index, the address of a cell, a cursor, see Theory of sequences and lists), and so does the cost of each operation, while (5) holds on all of them.

Contracts

A contract of an operation is a pair of a precondition \( P \) and a postcondition \( Q \), written \( \{ P \}\ \mathit{op}\ \{ Q \} \) after Hoare: the caller ensures \( P \), and the operation, under \( P \), ensures \( Q \); a structure has also an invariant \( I \), which each operation that changes it may assume at its start and must restore at its end, i.e., \( \{ P \land I \}\ \mathit{op}\ \{ Q \land I \} \). A violated precondition is a bug of the caller, a violated postcondition or invariant a bug of the operation (Meyer); in either case Contract.h throws contract_violation, a std::logic_error whose message names the kind of contract, the condition, the function and the place in the source.

Checking a contract costs time, and the costs differ by orders of magnitude: \( \mathrm{empty}() \) before a \( \mathrm{pop}() \) costs \( O( 1 ) \), the order of a heap after an insertion costs \( \Theta( n ) \), and that a vector is sorted before a binary search costs \( \Theta( n ) \) against the \( O( \log n ) \) of the search. A check of cost \( g( n ) \) added to an operation of cost \( t( n ) \) makes it cost \( O( t( n ) + g( n ) ) \), which is the same bound only if \( g( n ) = O( t( n ) ) \); an invariant of \( \Theta( n ) \) checked after each of \( k \) operations of \( O( 1 ) \) makes them cost \( \Theta( k n ) \), i.e., a linear algorithm quadratic. The library therefore sorts its checks by their cost with respect to the operation, and the level ADS_CONTRACTS chooses which are evaluated.

The contracts of Contract.h and the level from which each is checked
MacroContractIts costLevel
ADS_PREa preconditionat most that of the operation1 (the default, 0 with NDEBUG)
ADS_POSTa postconditionat most that of the operation2
ADS_INVARIANTthe invariant of a structureusually \( \Theta( n ) \)3
ADS_AUDITa precondition or a postconditionmore than the operation3

At the level 1 the bounds of the operations hold as stated, since every precondition checked costs no more than its operation; at the level 3 they do not, and the level is meant for the tests. A condition is compiled at every level, so that it stays correct C++, but it is evaluated only from its own level; hence it must have no side effects, since a program must behave in the same way at every level. The macros mirror the pre, post and contract_assert of the contracts of C++26, by which they can be replaced when the compilers have them.

Iterators

An iterator is a position in a container that can be read and moved to the next one, and the standard library sorts the iterators into categories by the moves they allow in \( O( 1 ) \) time; an algorithm states the category it needs (std::sort() a random-access iterator, std::reverse() a bidirectional one), and the iterators of Iterators.h give the containers of the library the category that their representation allows, so that the range-for, the algorithms of std and of std::ranges, and those of Boost visit them.

The iterators of Iterators.h and their categories
IteratorWalksCategoryCost of a step
LinkedIteratorcells linked by pointersforward\( O( 1 ) \)
IndexIteratorcells of a vector linked by indicesforward\( O( 1 ) \)
CircularIteratora circular vectorrandom access\( O( 1 ) \)
RankIteratora container read by rank, c[ i ]random accessthat of c[ i ]
IndirectIteratora vector of pointers, read through themrandom access\( O( 1 ) \)
SlotIteratorthe occupied places of a tablebidirectional\( O( m / n ) \) amortized over a whole visit
KeyIteratorthe keys of what another iterator readsthat of the other, up to bidirectionalthat of the other
PathIteratora binary tree in symmetric order, by the path from the rootbidirectional\( O( 1 ) \) amortized over a whole visit, \( O( h ) \) at most
WalkIteratorthe nodes of a tree by a policyforwardthat of the policy

A circular vector of capacity \( c \) whose first item is at the place \( \mathit{head} \) holds its item of index \( i \), counted from the head, at the place

\[ ( \mathit{head} + i ) \bmod c , \quad 0 \le i < n \le c , \tag{6} \]

so that CircularIterator keeps the index \( i \) rather than the place, its moves and its differences are those of the integers, and the order of the items is that of the queue rather than that of the places.

A table of \( m \) places of which \( n \) are occupied is visited by SlotIterator in \( \Theta( m ) \) time, since each place is examined once, i.e., in \( O( m / n ) \) amortized time per item, which is \( O( 1 ) \) when the load \( n / m \) is bounded from below by a constant, as in the hash tables that halve their table when they get too empty; a single step may examine \( \Theta( m ) \) places.

Lemma 2 (the visit in symmetric order by the path). Let PathIterator keep the path \( \pi \) from the root to the current node \( x \). The next node in symmetric order is the leftmost node of the right subtree of \( x \) if \( x \) has a right child, and otherwise the lowest ancestor of \( x \) whose left subtree contains \( x \); a whole visit of a tree of \( n \) nodes costs \( \Theta( n ) \), i.e., \( O( 1 ) \) amortized per step, and a single step costs \( O( h ) \).

Indeed, the nodes of the right subtree of \( x \) come right after \( x \), the leftmost first; if there is no right subtree, all the nodes below the ancestor \( y \) described come before \( y \) and \( x \) is the last of its left subtree, so that \( y \) follows \( x \). The path \( \pi \) gives the ancestors without links to the parents, and a step that goes down pushes the nodes it meets on \( \pi \), a step that goes up pops them. Each node is pushed once, when the visit first reaches it from its parent, and popped once, when the visit leaves its subtree; hence a whole visit makes \( n \) pushes and \( n \) pops, and since a step moves along one path from the root, it makes at most \( h \) of them. The path takes \( O( h ) \) space, against the link to the parent in every node that an iterator with no path needs, i.e., \( \Theta( n ) \) space; on a balanced tree \( h = O( \log n ) \).

Portable primitives

The product of two words of 64 bits is a number of 128 bits, which the processors give in one instruction and the languages do not; Wide.h takes it from Boost.Multiprecision, which uses that instruction, with ADS_WITH_BOOST, and otherwise computes it on the halves of 32 bits of the factors (wideProductHalves() of Portable.h). With \( a = a_1 2^{32} + a_0 \) and \( b = b_1 2^{32} + b_0 \), \( 0 \le a_0 , a_1 , b_0 , b_1 < 2^{32} \), one has

\[ a b = a_1 b_1 2^{64} + ( a_0 b_1 + a_1 b_0 ) 2^{32} + a_0 b_0 , \tag{7} \]

four products of 32 bits, each of which fits in 64 bits. The sum of the middle terms with the high half of \( a_0 b_0 \) is computed on the low halves of the middle products, i.e., as three numbers below \( 2^{32} \), whose sum is below \( 3 \cdot 2^{32} \) and fits in a word with no overflow; its high half is the carry into the high word of the product. The integers of any length of BigInteger.h call wideProductHalves() in place of the product of Boost when ADS_BIGINT_PORTABLE is defined, so that the library has one product of two words. The quotient of a number of two words by one (wideDivide()) is that of two digits of 32 bits by one, twice, after the divisor is shifted to its top bit, each estimate being corrected at most twice (Hacker's Delight, figure 9-3). In the same way, the signed integers of 128 bits are two words in two's complement, and the sum carries 1 into the high word exactly when the sum of the low words, modulo \( 2^{64} \), is smaller than either of them. These are details of the implementation, out of the API reference.

Typed modifications

A structure whose items have stable handles is, for the observers, a partial map \( \sigma \) from the handles to the states of the items, where the state of an item is the tuple of its attributes (its key, its value, and any other attribute \( A \), e.g., the cost of an arc), and \( \sigma( h ) = \bot \) when no item has the handle \( h \). An event of an item is a step of \( \sigma \) at one handle that carries both its ends: \( \mathrm{Inserted}( h , s ) \) takes \( \sigma( h ) \) from \( \bot \) to \( s \), \( \mathrm{Erased}( h , s ) \) from \( s \) to \( \bot \), and \( \mathrm{Changed}_A( h , a , b ) \) changes the attribute \( A \) of \( \sigma( h ) \) from \( a \) to \( b \); the events of the whole structure (\( \mathrm{Cleared} \), which makes \( \sigma \) empty, \( \mathrm{Rebuilt} \), after which any \( \sigma \) is possible, \( \mathrm{Shifted}_A( \delta ) \), which adds \( \delta \) to the attribute \( A \) of every item, \( \mathrm{Replaced}_A \) and the relocations) are not of one item. A sequence of events is a history of \( \sigma_0 \) when each event starts from the state that the previous ones leave. Since an event carries the old state as well as the new one, an observer that reads the events only, and not the structure, is correct whatever happened after them, and every event of an item has an inverse, the step back, which inverse() gives.

The net effect of a batch \( B \) is a sequence \( C \) that leads from \( \sigma_0 \) to the state to which \( B \) leads. The coalescing of Modification.h builds it in three steps: (i) everything before the last \( \mathrm{Cleared} \) or \( \mathrm{Rebuilt} \) is dropped, since the state after them does not depend on it; (ii) the events that are not of one item split what remains into runs, and they are kept in place, consecutive shifts of one attribute added into one (dropped if the sum is zero) and consecutive replacements of one attribute made one; (iii) within a run the events of each handle are reduced, in the order of their first event, by pushing them one by one on a list \( N \) of net events of the handle with the rules

\[\begin{array}{rcl} N \cdot \mathrm{Inserted}( h , s ) \cdot \mathrm{Erased}( h , s ) & \to & N , \cr \mathrm{Inserted}( h , s ) \cdot \mathrm{Changed}_A( h , a , b ) & \to & \mathrm{Inserted}( h , s[ A := b ] ) \quad A \in \{ \mathrm{Key} , \mathrm{Value} \} , \cr \mathrm{Changed}_A( h , a , b ) \cdot \mathrm{Changed}_A( h , b , c ) & \to & \mathrm{Changed}_A( h , a , c ) , \ \text{or nothing if } a = c , \cr \mathrm{Changed}_A( h , a , b ) \cdot \mathrm{Erased}( h , s ) & \to & \mathrm{Erased}( h , s[ A := a ] ) , \cr \mathrm{Erased}( h , s ) \cdot \mathrm{Inserted}( h , t ) & \to & \prod_{A : s_A \ne t_A} \mathrm{Changed}_A( h , s_A , t_A ) , \end{array} \tag{8} \]

where a change of an attribute moves past the changes of the other attributes of the handle (they commute, since they write disjoint parts of the state), a change with \( a = b \) (a touch) is dropped, and the last rule applies only when the structure emits the changes that it needs (a structure with no \( \mathrm{KeyChanged} \) keeps the erasure and the insertion of an item whose key differs). In the third rule \( c \) is the value of the reduction of \( A \): the last value by default, the least or the largest of \( b \) and \( c \) for an attribute whose changes are merged by a minimum or a maximum (the absolute values of a relaxation, which need not be a history), and \( b + ( c - b' ) \) for one whose changes add up, \( b' \) being the old value of the second change.

Lemma 1. Let \( B \) be a history of \( \sigma_0 \) whose attributes have the reduction last, and \( C \) its net effect by (i), (ii) and (iii). Then \( C \) is a history of \( \sigma_0 \) that leads to the state to which \( B \) leads, \( |C| \le |B| \), and \( C \) is built in \( O( |B| ) \) expected time when the number of kinds of event is a constant.

Proof. Step (i) is correct because \( \mathrm{Cleared} \) and \( \mathrm{Rebuilt} \) start from any state. The events of different handles within a run commute, since each reads and writes the state of its own handle only; hence a run can be replayed handle by handle, and it suffices that each rule of (8) replaces two steps at one handle by steps that lead from the same state to the same state. The first rule takes \( \bot \) to \( s \) and back; the second inserts directly the state after the change; the third composes two changes of one attribute, and vanishes when the attribute returns to its value; the fourth erases from the state before the change, which is the state that the erasure of the history takes away, the attribute restored; the fifth goes from \( s \) to \( t \) by one change per attribute that differs. Each rule leaves at most as many events as it takes, so that \( |C| \le |B| \), and a list \( N \) holds at most one insertion or erasure and one change per attribute (plus an erasure and an insertion when the changes are missing), a constant; a hash table on the handles finds the list of each event in \( O( 1 ) \) expected time. \( \square \)

The global events cannot be moved past the events of the items, since an item inserted with an absolute key after a shift would be shifted twice; they bound the runs instead of going last. A relocation and a permutation change the meaning of the handles, and bound the runs for the same reason.

A mutator tests two predicates before it builds an event of the kind \( E \): listened< E >, a constant of the subject, false for NoObservers and for static observers with no on() of \( E \), in which case the event, the read of the old state and the test vanish at compile time; and live< E >(), true when some observer wants \( E \) now (a constant for a static observer with no mask, a test of the bit of \( E \) in the union of the masks for the dynamic ones). The path that builds and sends the event is a cold function out of line when the subject is dynamic, so that the change with nobody attached costs the load and the test of the mask; bench/zerocost.py checks both claims by the instructions that callgrind counts and by the code of the changes, which with NoObservers is that of the plain structure byte for byte, and with a static observer that does not want the kind that of NoObservers.

Outside a batch an insertion and a change are told after the change, an erasure before it; on() of the erasures and of the global events that lose information must not throw. When an on() of an insertion or a change throws, the observers already told get the inverse event in the reverse order, the structure undoes its own change and the exception goes on; this is the strong guarantee of Abrahams whenever the undo of the structure does not throw, and prepare() gives it with no undo, since it refuses before anything changes. A batch tells nothing before its close, so that a batch left by an exception is discarded: the structure goes back to its checkpoint if it has one, and the observers get \( \mathrm{Rebuilt} \) otherwise. UndoLog keeps the events of a history, from which the inverses in the reverse order give a history back to any of its checkpoints.

Capabilities

An algorithm that takes a structure as a type may ask what the structure can do, and choose its faster path at compile time; Capabilities.h gives the vocabulary of these questions, which is of three kinds because the answers are of three kinds. A concept of C++20 decides a question of syntax (whether split() exists and what it takes), but not one of meaning: a structure whose rank() scans its items satisfies the same concept as one whose rank() reads a counter, and the items of a heap that moves them satisfy the same requirements as those of a heap of nodes. The second kind is therefore an explicit opt-in of the structure, a variable template that it specializes (enable_stable_references< S >, as std::ranges::enable_borrowed_range of the standard) or a static member that it declares (Q::decrease_key, S::monotone); a structure that says nothing gets the conservative answer. The third kind is a property that a wrapper must pass on without knowing it, since a wrapper written today cannot list the properties of tomorrow: a query s.query( tag ), answered by the structure if it has a static member for the tag and by the default of the tag otherwise, which ObservedGraph forwards to its graph and Shadow composes from its two observers by the meet of the tag (the conjunction for the stable references and for the reads that may run with writes, the worse of the two classes of time for rank()), as the environments of P2300 forward their queries.

The customization point objects of Niebler are used only where a type that ADS does not own may lack an operation that has a sensible default: reserve( s , n ) does nothing for a std::list, prefetch( s , k ) does nothing where no prefetch is known, and insert_bulk( s , r ) inserts the items one by one; each calls the member if there is one, else a free function found by argument-dependent lookup, else the default. The three of the priority queues in QueueCustomization.h read the members of the book first and the spelling of the standard last, so that std::priority_queue models the base PriorityQueue as it is.

A priority queue lowers the key of an item in one of two ways, and decrease_key_of< Q >() tells them apart: natively, by decrease() on the handle that the insertion gave, or lazily, by a new insertion of the item with the lower key, the older copies left in the queue and skipped when they come out. Neither is better in general: the lazy form needs no handles and no table of positions, at the price of a queue that holds one copy per decrease instead of one per item, and on sparse graphs it is often the faster of the two (Chen et al.). The shortest paths of ShortestPaths.h and Prim's algorithm of MinimumSpanningTree.h take either; in the lazy case the frontier keeps, for each node, whether it is in \( S \), and skips a copy whose node is not. The native form is read through queue_decrease( q , h , p ), the member decrease() of a queue with the handles of the book or a free function found by argument-dependent lookup, so that a mutable heap of another library (the heaps of Boost.Heap, by ADS/interop/boost/Heap.h, where a decrease in the sense of ADS is the increase() of Boost, toward the top) lowers its keys natively with no wrapper.

Lemma 2. Let the priorities of the copies be the pairs \( ( d , v ) \) of a distance and a node, inserted at each fall of the distance of \( v \). Then the lazy frontier extracts the same nodes, in the same order and with the same counts, as a native one on the same graph.

Proof. The distance of a node only falls, so that the last copy of \( v \) inserted has the least priority among the copies of \( v \) in the queue; while \( v \) is in \( S \), that copy is the one with the priority \( ( d_v , v ) \) which the native queue holds. When \( v \) leaves \( S \) its other copies have larger priorities and are skipped, and if \( v \) enters \( S \) again (with negative weights) its new copy is again the least of its copies. Hence at each extraction the least copy of a node in \( S \) is the least entry of the native queue, the pairs being distinct, and the stale copies before it are skipped without counting; the additions and the decreases are the calls of the prototype, the same in both. \( \square \)

The algebra of the aggregates

A structure that keeps an aggregate, i.e., the combination \( a_1 \oplus \cdots \oplus a_n \) of some values by an associative operation with an identity \( e \) (the prefix sums of an array, the aggregate of a window, the augmentation of a tree), must update it when a value enters, leaves or changes, and the cheapest rule depends on the algebra of \( \oplus \), not on the structure. Algebra.h names the algebras by concepts on static members of the type G that defines \( \oplus \): a Monoid has identity() and combine(); a CommutativeMonoid declares commutative; a Group has inverse(); a Selective monoid declares selective, the promise that \( a \oplus b \in \{ a , b \} \); an Action of maps on a monoid has the identity map, the composition and the application of a map to the aggregate of \( n \) values, the ingredients of the lazy updates of a range. The flags are opt-ins, since no syntax shows that an operation commutes or selects, and the existing augmentations of JoinTree, which have identity(), from() and combine(), are monoids as they are. The concepts do not prove the laws, which the tests check on the algebras of ADS (the sums, the minima, the maxima) and on an operation that does not commute for each concept that does not require it.

Lemma 3. Let \( c = x \oplus a \oplus y \) be an aggregate in which the value \( a \) is replaced by \( b \), and \( c' = x \oplus b \oplus y \). (i) In an abelian group, \( c' = c \oplus a^{-1} \oplus b \). (ii) In a commutative monoid, if \( b = a \oplus d \) then \( c' = c \oplus d \). (iii) In a group, if \( x = e \) then \( c' = b \oplus a^{-1} \oplus c \); if \( y = e \), \( c' = c \oplus a^{-1} \oplus b \). (iv) In a selective monoid, the aggregate of any values is one of them, or \( e \) if there is none.

Proof. (i) By commutativity \( c = a \oplus x \oplus y \), so that \( c \oplus a^{-1} \oplus b = a \oplus a^{-1} \oplus x \oplus y \oplus b = x \oplus b \oplus y \). (ii) \( c \oplus d = x \oplus y \oplus a \oplus d = x \oplus ( a \oplus d ) \oplus y \). (iii) With \( x = e \), \( b \oplus a^{-1} \oplus c = b \oplus a^{-1} \oplus a \oplus y = b \oplus y \), and symmetrically with \( y = e \), by associativity alone. (iv) By induction on the number of operands, each combination being one of its two operands. \( \square \)

Lemma 3 is the dispatch of the structures: (i) is the update of a prefix sum by its difference (Fenwick, see Prefix aggregates of an observable array) and the free partial retroactivity of an abelian group, (ii) the add() of a commutative monoid (a maximum raised), (iii) the removal of the first value of a window and the insertion of the last (subtract-on-evict, see The aggregate of a sliding window), which needs no commutativity, and (iv) the monotone deque of a window of minima. A monoid with none of these properties can only recombine the parts that the change touched, which the structures do in \( O( \log n ) \) combinations (a tree) or in \( O( 1 ) \) amortized (two stacks). When the values are not exact (exact_v false, i.e., floating point) the inverse of (i) and (iii) does not undo the rounding of the combination, and a group aggregate drifts; the structures then recompute it from the values every period() updates, at \( O( 1 ) \) amortized cost when the period is at least the number of values, and their audits catch a drift beyond the tolerance of a test.

References

See also
A. Montresor, Algoritmi e Strutture Dati, 2025, chapters 3 and 4, https://algoritmicamente.it/materiali/libro/capitoli/cap03.pdf and https://algoritmicamente.it/materiali/libro/capitoli/cap04.pdf
K. Tangwongsan, M. Hirzel, S. Schneider, In-order sliding-window aggregation in worst-case constant time, The VLDB Journal 30(6), 933-957, 2021, doi:10.1007/s00778-021-00668-3
M. Budiu, T. Chajed, F. McSherry, L. Ryzhyk, V. Tannen, DBSP: automatic incremental view maintenance for rich query languages, Proceedings of the VLDB Endowment 16(7), 1601-1614, 2023, doi:10.14778/3587136.3587137
B. Liskov, S. Zilles, Programming with abstract data types, ACM SIGPLAN Notices 9(4), 50-59, 1974, doi:10.1145/942572.807045
D. L. Parnas, On the criteria to be used in decomposing systems into modules, Communications of the ACM 15(12), 1053-1058, 1972, doi:10.1145/361598.361623
J. V. Guttag, J. J. Horning, The algebraic specification of abstract data types, Acta Informatica 10(1), 27-52, 1978, doi:10.1007/BF00260922
C. A. R. Hoare, An axiomatic basis for computer programming, Communications of the ACM 12(10), 576-580, 1969, doi:10.1145/363235.363259
B. Meyer, Applying "design by contract", Computer 25(10), 40-51, 1992, doi:10.1109/2.161279
J. Berne, T. Doumler, A. Krzemienski et al., Contracts for C++, P2900R14, ISO/IEC JTC1/SC22/WG21, 2025
B. Stroustrup, The C++ Programming Language, 4th ed., Addison-Wesley, 2013, chapter 33 (the iterators)
D. Abrahams, Exception-safety in generic components, Generic Programming, LNCS 1766, 69-79, 2000, doi:10.1007/3-540-39953-4_6
E. Niebler, Suggested design for customization points, ISO/IEC JTC1 SC22 WG21 N4381, 2015, https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4381.html
M. Dominiak, G. Evtushenko, L. Baker, L. R. Teodorescu, L. Howes, K. Shoop, M. Garland, E. Niebler, B. A. Lelbach, std::execution, ISO/IEC JTC1 SC22 WG21 P2300R10, 2024, https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2024/p2300r10.html
M. Chen, R. A. Chowdhury, V. Ramachandran, D. Lan Roche, L. Tong, Priority queues and Dijkstra's algorithm, Technical Report TR-07-54, The University of Texas at Austin, 2007, https://www3.cs.stonybrook.edu/~rezaul/papers/TR-07-54.pdf
U. A. Acar, G. E. Blelloch, R. Harper, Adaptive functional programming, Proceedings of POPL, 247-259, 2002, doi:10.1145/503272.503296
T. A. Davis, Algorithm 1000: SuiteSparse:GraphBLAS: graph algorithms in the language of sparse linear algebra, ACM Transactions on Mathematical Software 45(4), 1-25, 2019, doi:10.1145/3322125