|
ADS
Algorithms and Data Structures
|
The headers of include/ADS/graph realize the GRAPH of chapter 9 of the book and the algorithms of chapters 9, 11, 13, 14 and 15 that work on it, i.e., the visits, the shortest paths, the minimum spanning trees, the maximum flows and a few problems that reduce to them. This page collects what the headers take for granted: the definitions and the notation shared by all of them (see Definitions and notation), the representations and the costs of their operations (see Representations and their costs), and, for each family of algorithms, the property on which its correctness rests and the argument behind its bound (from Visits to Eulerian trails and other properties), and, beyond the book, the solutions kept up to date through the changes of the graph (see Changes of the graph and reoptimization), the assignment problem with its reoptimization (see The assignment and its reoptimization) and the policy that chooses between a repair and a computation from scratch (see The recompute policy of the observers). The pseudocode of each algorithm is instead on the page of its header, in the comment of its function, together with the section of the book, or the paper, that it follows.
A graph \( G = ( V , E ) \) has a set \( V \) of \( n \) nodes and a set \( E \) of \( m \) edges; an edge of an oriented graph is an ordered pair \( ( u , v ) \), which leaves \( u \) and enters \( v \), and an edge of an unoriented graph is an unordered pair \( [ u , v ] \), which the library stores as the two pairs \( ( u , v ) \) and \( ( v , u ) \) (section 9.2 of the book). There are no loops \( ( u , u ) \), and hence \( 0 \le m \le n ( n - 1 ) \); a graph is said sparse when \( m \) is of the order of \( n \) and dense when it is of the order of \( n^2 \), which is the distinction that decides between the representations (see Representations and their costs). The nodes are named by the integers in \( [ 0 , \mathrm{bound}() ) \), a deleted node leaving its name unused, so that the vectors indexed by the nodes have \( \mathrm{bound}() \ge n \) places.
| Symbol | Meaning |
|---|---|
| \( \mathrm{adj}( u ) \) | the nodes \( v \) with \( ( u , v ) \in E \), the SET of the book; \( d( u ) = | \mathrm{adj}( u ) | \) is the (out)degree of \( u \), and \( \sum_u d( u ) = m \) (\( 2 m \) for an unoriented graph) |
| \( w( u , v ) \) | the weight, or cost, or length, of the edge \( ( u , v ) \), of the type W of the graph |
| \( \delta( r , v ) \), \( d[ v ] \) | the distance from \( r \) to \( v \) (the fewest edges, or the least total cost, of a path), and the value that an algorithm keeps for it; \( \infty \) (INF, infinity()) when \( v \) is not reachable |
| \( p[ v ] \), \( T[ v ] \) | the parent of \( v \) in a tree rooted at the source, as a vector of parents, NIL for the root and the nodes not reached |
| \( \mathit{dt}[ u ] \), \( \mathit{ft}[ u ] \) | the discovery and the finish times of \( u \) in a visit in depth, on one clock that each event advances by 1 |
| \( c( u , v ) \), \( f( u , v ) \), \( c_f( u , v ) \) | the capacity of an edge of a network, the flow on it, and the residual capacity \( c( u , v ) - f( u , v ) \) |
| \( ( S , V \setminus S ) \) | a cut, the edges with one end in \( S \) and the other out of it |
A path from \( u \) to \( v \) is a sequence of nodes \( u = x_0 , x_1 , \ldots , x_k = v \) with \( ( x_{i-1} , x_i ) \in E \); it is simple if its nodes are distinct, and it is a cycle if \( k \ge 1 \) and \( u = v \) (\( k \ge 3 \) for an unoriented graph). A graph with no cycle is acyclic (a DAG if oriented, a forest if not, a free tree if it is also connected). The nodes reachable from one another, the orientation ignored, form the connected components, and those reachable from one another along the orientation the strongly connected components.
The library has five realizations of the GRAPH, which differ in the space and in the time of the operations. The algorithms of the area are written on the concept Graph of Graph.h, i.e., on V(), adj( u ) and forEachAdj( u , f ), and their bounds hold on lists or vectors of adjacency, where the scan of \( \mathrm{adj}( u ) \) costs \( \Theta( d( u ) + 1 ) \).
| Realization | Space | hasEdge( u , v ) | scan of adj( u ) | insert or delete an edge |
|---|---|---|---|---|
| MatrixGraph | \( \Theta( n^2 ) \) | \( O( 1 ) \) | \( \Theta( n ) \) | \( O( 1 ) \) |
| ListGraph | \( \Theta( n + m ) \) | \( O( d( u ) ) \) | \( \Theta( d( u ) + 1 ) \) | \( O( d( u ) ) \) |
| ArrayGraph, StaticGraph | \( \Theta( n + m ) \) | \( O( d( u ) ) \) (\( O( \log d( u ) ) \) on StaticGraph, whose rows are sorted) | \( \Theta( d( u ) + 1 ) \), one contiguous run | none, the graph is static |
| PointerGraph | \( \Theta( n + m ) \) | \( O( d( u ) ) \) | \( \Theta( d( u ) + 1 ) \) | \( O( d( u ) ) \) |
| GridGraph | one cost per cell, or none | \( O( 1 ) \) | \( O( 1 ) \), at most 8 cells | none, the moves are computed |
A matrix is usually preferable on the dense graphs and when hasEdge() dominates (e.g., universalSink() of Properties.h reads at most \( 3 ( n - 1 ) \) entries of it); on a sparse graph a visit costs \( \Theta( n^2 ) \) on the matrix against \( \Theta( n + m ) \) on the lists, since each row is read whole. Among the static realizations, StaticGraph keeps the heads and the weights of the arcs in two arrays of the same places, the offsets of the rows in a third (the arrays of a graph in compressed rows that METIS and GraphBLAS take as they are), and sorts the arcs of each node by head, so that a visit reads the memory forward and reads no weight when it needs only the heads (cf. StaticGraph.h, whose second parameter ArcLayout::Interleaved keeps instead the pairs of a head and its weight in one array, for the algorithms that read both); both are built from a list of edges by counting sort in \( \Theta( n + m ) \), since the keys are the names of the nodes, i.e., integers in \( [ 0 , n ) \). The counting sort by tail of ArrayGraph is stable, and hence its rows keep the order in which the edges were given, while StaticGraph sorts them by head with a first pass on the heads; GraphBuilder of GraphBuilder.h collects the edges of a graph built one at a time and freezes it into either form at that cost.
The generic visit of section 9.5 (genericVisit() of Visit.h) keeps the reached nodes \( R \), the open ones \( Q \subseteq R \) and a tree \( B \): at each step it takes a node \( j \) of \( Q \) and either reaches a node \( k \in \mathrm{adj}( j ) \setminus R \), adding \( ( j , k ) \) to \( B \), or closes \( j \). A node enters \( R \) once, and a cursor in \( \mathrm{adj}( j ) \) never goes back; hence each node is taken \( O( 1 + d( j ) ) \) times, each edge is examined once from its tail, and a visit costs \( \Theta( n + m ) \) time on lists. At the end \( R \) holds the nodes reachable from the root, and \( B \) is a tree that spans them, with one edge less than \( R \) (an invariant of the loop, checked at the level of the audits). Taking the oldest node of \( Q \) gives the visit in breadth, and taking the newest the visit in depth.
Lemma 1 (the visit in breadth). With \( Q \) a queue, \( d[ v ] = d[ u ] + 1 \) set when \( v \) is reached from \( u \), and \( d[ r ] = 0 \), one has at the end
\[ d[ v ] = \delta( r , v ) \quad \forall v \in V . \tag{1} \]
Indeed, the values of \( d \) in the queue never decrease from its head to its tail and differ by at most 1. A node at distance \( k \) is therefore dequeued before any node at distance \( k + 1 \) is reached, and by induction on \( k \) a node \( v \) with \( \delta( r , v ) = k + 1 \) is first reached from a node \( u \) at distance \( k \), which gives (1). Hence distance() of Visit.h gives the shortest paths in edges in \( \Theta( n + m ) \), and its tree of the parents is a tree of shortest paths. The same argument holds with several sources at distance 0 (multiSourceDistance() of Paths.h and gridDistances() of Grid.h). Also, countShortestPaths() of Paths.h adds to the count of \( v \) that of each \( u \) with \( d[ v ] = d[ u ] + 1 \), and by the same order of the levels the count is complete when \( v \) is dequeued.
Lemma 2 (the visit in depth). In a visit in depth the intervals \( [ \mathit{dt}[ u ] , \mathit{ft}[ u ] ] \) of two nodes are either disjoint or nested, and \( v \) descends from \( u \) in the forest of the visit if and only if its interval lies in that of \( u \). Classifying an edge \( ( u , v ) \) when it is examined, as DfsSchema of Visit.h does, gives
\[ \begin{array}{ll} \text{tree} & \mathit{dt}[ v ] = 0 , \cr \text{back} & \mathit{dt}[ u ] > \mathit{dt}[ v ] \text{ and } \mathit{ft}[ v ] = 0 , \cr \text{forward} & \mathit{dt}[ u ] < \mathit{dt}[ v ] \text{ and } \mathit{ft}[ v ] \ne 0 , \cr \text{cross} & \text{otherwise,} \end{array} \tag{2} \]
and an oriented graph has a cycle if and only if a visit finds a back edge.
In fact, the nesting holds since the visit of \( v \) either starts and ends while \( u \) is on the stack, or does not start before \( u \) is finished. A back edge \( ( u , v ) \) closes a cycle with the path of the tree from \( v \) to \( u \). Conversely, if \( v \) is the first node of a cycle to be discovered, the other nodes of the cycle are reached before \( v \) is finished (the path of white nodes of Tarjan); the edge of the cycle that enters \( v \) is then examined while \( v \) is on the stack, i.e., it is a back edge. Note that on an unoriented graph each edge, met again from its other end, is a back edge in the sense of (2), and hasCycle() returns true as soon as the graph has an edge.
Next, the finish times give a topological order. If the graph is acyclic, each edge \( ( u , v ) \) has
\[ \mathit{ft}[ v ] < \mathit{ft}[ u ] , \tag{3} \]
since by (2) it is a tree, forward or cross edge, and \( v \) is finished before \( u \) in all three cases; hence the nodes by decreasing finish time are in a topological order (topsort()). The algorithm of Kahn (topsortKahn()) reaches the same goal by removing, at each step, a node with no entering edge, which an acyclic graph always has. With the counts of the entering edges kept in a vector it costs \( \Theta( n + m ) \), and it stops with fewer than \( n \) nodes if and only if a cycle remains. The topological order is unique if and only if the set of the sources never holds two nodes (uniqueTopologicalOrder() of Properties.h), i.e., if and only if consecutive nodes of the order are joined by an edge.
Lemma 3 (Kosaraju). Let \( C \) and \( C' \) be two strongly connected components, and \( \mathit{ft}( C ) \) the largest finish time of a node of \( C \) in a visit in depth of \( G \). If an edge goes from \( C \) to \( C' \), then \( \mathit{ft}( C ) > \mathit{ft}( C' ) \) (Theorem 9.1 of the book).
Therefore, a visit of the transposed graph \( G^T \) started from the node of largest finish time stays in its component, since an edge that leaves it in \( G^T \) can only enter a component already visited; the next visit, from the largest finish time left, does the same. Thus, scc() of Visit.h costs two visits, each \( \Theta( n + m ) \), and the copy of the transposed graph. The graph of the components is acyclic, and unilaterallyConnected() tests whether its topological order is unique.
One visit in depth suffices, if the components are recognized as it finishes them (Tarjan, beyond the book). The root of a component \( C \) is its node \( r_C \) discovered first; by Lemma 2 every node of \( C \) is a descendant of \( r_C \), since all of them are undiscovered when \( r_C \) is discovered and reachable from it. The visit pushes each node it discovers on a stack \( S \), and keeps \( \mathit{low}[ u ] \), the least \( \mathit{dt} \) of a node of \( S \) that the subtree of \( u \) reaches by its tree edges and one more edge, \( \mathit{dt}[ u ] \) itself included.
Lemma 4 (the roots of Tarjan). When \( u \) finishes, \( u \) is a root if and only if \( \mathit{low}[ u ] = \mathit{dt}[ u ] \); the nodes above \( u \) on \( S \) are then exactly the nodes of its component.
Indeed, if \( u \) is not a root, the root \( r \) of its component is a proper ancestor of \( u \), still open and on \( S \), and a path from \( u \) to \( r \) leaves the subtree of \( u \) by an edge \( ( x , y ) \) whose head \( y \) reaches \( r \); the component of \( y \) is that of \( r \), which is not closed, so that \( y \) is on \( S \) with \( \mathit{dt}[ y ] < \mathit{dt}[ u ] \), and \( \mathit{low}[ u ] < \mathit{dt}[ u ] \). Conversely, if \( \mathit{low}[ u ] < \mathit{dt}[ u ] \) the subtree of \( u \) reaches a node \( y \) of \( S \) discovered before \( u \); the nodes of \( S \) discovered before \( u \) are in components still open, whose roots are ancestors of \( u \), so that the root of the component of \( y \) reaches \( u \) by the tree and is reached from \( u \) through \( y \): \( u \) is in a component opened before it, and is not a root. Finally, when the root \( u \) finishes, the nodes above it on \( S \) are its descendants not yet closed, and a descendant in another component would have a root between \( u \) and itself, which has closed it before. The test of \( y \in S \) is that \( y \) has no component yet, so that the visit costs \( \Theta( n + m ) \) (sccTarjan() of StrongComponents.h): each node is pushed and popped once, and each edge examined once. When a component closes, every component that it reaches is closed already; hence the components close in the reverse of a topological order of their graph, and sccTarjan() numbers them backwards, as scc() numbers them: an edge from \( C \) to \( C' \ne C \) gives \( C < C' \). The recursion is kept on a stack of the pairs (node, next edge), and the adjacencies are read once into compressed rows, so that the cost holds on every model of Graph and a path of \( 10^6 \) nodes does not overflow the stack of the calls.
The visit of Tarjan keeps three integers per node (\( \mathit{dt} \), \( \mathit{low} \) and the component); Pearce keeps one, and a bit (sccPearce()). The integer \( \mathit{rindex}[ u ] \) starts as the order of discovery and takes, instead of \( \mathit{low}[ u ] \), every smaller \( \mathit{rindex} \) met, the bit recording whether it took one; when \( u \) closes its component, its nodes take the number \( c \) of the component, which counts down from \( N - 1 \), and the counter \( i \) of the discoveries goes back by one per node closed.
Lemma 5 (one integer per node). The numbers of the open nodes are at most \( c + 1 \), and those of the closed ones at least \( c + 1 \).
Indeed, an open node has a number below \( i \), and \( i - 1 \) counts the open nodes, which are at most the \( c + 1 \) names of the \( N \) not closed, the closed ones being \( N - 1 - c \); the closed nodes have the numbers \( c + 1 , \ldots , N - 1 \) of their components. Hence a comparison of the numbers alone never lets a closed node lower an open one, as the test \( y \in S \) of Lemma 4 does, and a node of \( S \) belongs to the component of the root \( u \) if and only if its number is at least \( \mathit{rindex}[ u ] \); the visit makes the same choices as that of Tarjan, in the same time, with \( N \) words and \( N \) bits besides the two stacks, and the components numbered \( \mathit{rindex}[ u ] - c \) at the end come out in the order of sccTarjan().
With a cost \( w( u , v ) \) on each edge and a source \( r \), a tree \( T \) rooted in \( r \), with \( d[ v ] \) the cost of its path from \( r \) to \( v \), is a tree of shortest paths if and only if (theorem of Bellman, Theorem 11.1 of the book)
\[ d[ v ] = d[ u ] + w( u , v ) \quad \forall ( u , v ) \in T , \qquad d[ u ] + w( u , v ) \ge d[ v ] \quad \forall ( u , v ) \in E , \tag{4} \]
provided that no cycle of negative cost is reachable from \( r \) (with one, no shortest path exists). The prototype of section 11.2 (shortestPaths() of ShortestPaths.h) starts from \( d[ r ] = 0 \) and \( d[ v ] = \infty \) elsewhere and, while an edge violates (4), sets \( d[ v ] = d[ u ] + w( u , v ) \) and makes \( u \) the parent of \( v \); a structure \( S \) holds the nodes whose edges have to be checked again. Each \( d[ v ] \) is at all times the cost of some path from \( r \), and it only decreases; hence, when \( S \) is empty, (4) holds and \( d \) is optimal. The kind of \( S \) decides how many times a node is extracted, and therefore the cost.
| \( S \) | Algorithm | Time | Negative costs |
|---|---|---|---|
| priority queue on an unsorted list | Dijkstra | \( O( n^2 ) \) | correct, a node possibly extracted more than once |
| binary heap | Johnson | \( O( m \log n ) \) | as above |
| Fibonacci heap | Fredman and Tarjan | \( O( m + n \log n ) \) | as above |
| queue | Bellman, Ford and Moore | \( O( n m ) \) | a negative cycle detected |
| stack, deque | Pape and D'Esopo (deque) | exponential in the worst case | no negative cycle allowed |
With nonnegative costs and \( S \) a priority queue on \( d \), the node \( u \) extracted has \( d[ u ] = \delta( r , u ) \): any other path to \( u \) leaves the extracted nodes through a node of \( S \) of priority at least \( d[ u ] \), and goes on with costs that are not negative. Hence each node is extracted once and each edge is examined once, and the time is that of \( n \) extractions and of at most \( m \) decreases of a priority, i.e., \( n \cdot O( n ) + m \cdot O( 1 ) \) on the unsorted list, \( ( n + m ) \cdot O( \log n ) \) on the binary heap and \( n \cdot O( \log n ) + m \cdot O( 1 ) \) amortized on the Fibonacci heap. With a queue, the nodes extracted in the \( k \)-th round (those that entered \( S \) in the round before) have their final distance if one of their shortest paths has at most \( k \) edges. A shortest path has at most \( n - 1 \) edges; hence each node leaves the queue at most \( n \) times, the time is \( O( n m ) \), and a node extracted more than \( n \) times proves that a negative cycle is reachable (exercise 11.2). On an acyclic graph one can do better, whatever the signs of the costs: the scan of the nodes in topological order relaxes the edges of each node once, after all the edges that enter it, and (4) holds in \( O( n + m ) \) (dagShortestPaths(); the longest paths of dagLongestPaths() of Paths.h follow the same recurrence with the maximum).
Between all the pairs of nodes, with \( d^k[ u ][ v ] \) the least cost of a path from \( u \) to \( v \) whose inner nodes are among the first \( k \), one has (section 13.5)
\[ d^k[ u ][ v ] = \min\{ d^{k-1}[ u ][ v ] , d^{k-1}[ u ][ k ] + d^{k-1}[ k ][ v ] \} , \tag{5} \]
since such a path either avoids the node \( k \) or passes through it once (no cycle being negative); floydWarshall() of AllPairsShortestPaths.h fills (5) in place, in \( \Theta( n^3 ) \) time and \( \Theta( n^2 ) \) space, and a negative cycle shows as \( d[ u ][ u ] < 0 \). After the insertion of an edge \( ( a , b ) \) a path that improves uses it once, and the update \( d[ u ][ v ] \gets \min\{ d[ u ][ v ] , d[ u ][ a ] + w + d[ b ][ v ] \} \) costs \( O( n^2 ) \) (addEdge()); a deletion has no such update.
A grid map of \( R \times C \) cells, each free or blocked, is the graph whose nodes are the free cells and whose edges are the moves from a cell to the free cells at its four sides or, with eight moves, also at its four corners (the tiles and the octiles in the terms of Yap). The programs of best-first search on such maps do not build this graph. The maps of the benchmarks of Sturtevant are text files, a header with the height and the width followed by one character per cell, and the fast searchers keep them as one flat array of the cells in the order of the rows, one byte or one bit per cell and often with a border of blocked cells, name the cell \( ( r , c ) \) by its index \( r C + c \), and compute the neighbors by the offsets \( \pm 1 \), \( \pm C \) and \( \pm C \pm 1 \). Jump point search (Harabor and Grastien) is built on this access: it prunes the neighbors of a cell by the direction of the move that reached it and jumps along the rows and the columns, reading only whether a cell is free, and its improved version reads a word of cells of a row at once from a bitmap of the map (with a transposed copy for the columns), or looks the lengths of the jumps up in tables computed in advance. Lists of adjacency would hold up to \( 8 n \) arcs that the offsets give for free, and would add a read of memory to each neighbor.
GridGraph of GridGraph.h keeps the map as a vector of costs, a cell blocked if its cost is not positive (with one byte per cell for the maps of the benchmarks, and no vector at all for a free map of unit costs), and names the cell \( ( r , c ) \) by \( r C + c \) with no border, so that the names are those of the map; the row and the column of a node, one division, replace the border in the tests on the bounds. With \( \gamma( v ) \) the cost of the cell \( v \), a move from \( u \) into \( v \) costs \( \gamma( v ) \, a \) to a side and \( \gamma( v ) \, b \) to a corner when the cell entered pays (the default of MoveCost), and \( \gamma( u ) \, a \) and \( \gamma( u ) \, b \) when the cell left pays, \( a = 1 \) and \( b = \sqrt{2} \) in the benchmarks (the octile costs); a move to a corner either may cut it, or needs one of its two sides free, or needs both (the rule of the benchmarks since 2012). All three rules are symmetric in the two ends of a move, and hence, under both models, the graph is unoriented when the free cells cost the same and oriented otherwise. With \( w_1( u , v ) \in \{ a , b \} \) the cost of a move on a map of unit costs, a path \( x_0 , x_1 , \ldots , x_k \) costs \( \sum_{i = 1}^{k} \gamma( x_i ) \, w_1( x_{i-1} , x_i ) \) when the cell entered pays and \( \sum_{i = 1}^{k} \gamma( x_{i-1} ) \, w_1( x_{i-1} , x_i ) \) when the cell left pays, i.e., as much as the reversed path in the first model; hence the distances from \( s \) in the second model are the distances to \( s \) in the first. With four moves every \( w_1 \) is \( a \) and the two costs of a path from \( s \) to \( t \) differ by \( a ( \gamma( s ) - \gamma( t ) ) \), the same for all such paths, so that the two models have the same shortest paths; with eight moves the weight \( b \) of a corner falls on a different cell in the two models, and their shortest paths may differ.
Lemma 6 (the octile distance). On a grid with no blocked cell and eight moves of costs \( a \) and \( b \) with \( a \le b \le 2 a \), let \( M \) and \( \mu \) be the larger and the smaller of \( | r - r' | \) and \( | c - c' | \); the least cost of a path from \( ( r , c ) \) to \( ( r' , c' ) \) is
\[ h = a ( M - \mu ) + b \, \mu , \tag{6} \]
and on any grid of the same moves, with costs \( \gamma( v ) \ge \gamma_{\mathrm{min}} \) of the cells, some of them blocked and either the cell entered or the cell left paying for a move, \( \gamma_{\mathrm{min}} h \) is a consistent lower bound on the cost to \( ( r' , c' ) \).
Indeed, a path of \( x \) moves to a side and \( y \) to a corner has \( x + y \ge M \), since each move brings the larger gap down by at most 1, and \( x + 2 y \ge M + \mu \), since a move to a corner brings the sum of the two gaps down by at most 2 and one to a side by at most 1; the least of \( a x + b y \) on these constraints is at one of the vertices \( ( M - \mu , \mu ) \), \( ( M + \mu , 0 ) \) and \( ( 0 , M ) \), and \( a \le b \le 2 a \) makes the first one the least, which a path of \( \mu \) diagonal moves and \( M - \mu \) straight ones attains. Hence (6) is the distance of a graph, which satisfies the triangle inequality, i.e., \( h( u ) \le w_1( u , v ) + h( v ) \) for each move of cost \( w_1( u , v ) \in \{ a , b \} \) on the free grid; since a move of the weighted grid costs \( w( u , v ) = \gamma( x ) \, w_1( u , v ) \ge \gamma_{\mathrm{min}} \, w_1( u , v ) \), \( x \) the cell that pays (\( v \) or \( u \)), and the blocked cells only remove moves, the bound \( \gamma_{\mathrm{min}} h \) is consistent, and so admissible, on every such grid. With \( b = a \) (the moves of the king) (6) is the distance of Chebyshev \( a M \), and with four moves the same argument with \( y = 0 \) gives that of Manhattan \( a ( M + \mu ) \) (gridHeuristic(), which takes \( \min\{ b , 2 a \} \) as the cost of a corner). The A* of Hart, Nilsson and Raphael with a consistent bound never takes a node out of its queue twice, and with (6) on a map with few obstacles it usually examines far fewer cells than Dijkstra's algorithm, with the same bound in the worst case.
The visits of the library run on GridGraph as on any other Graph, since the free cells are its nodes and the names of the cells its range \( [ 0 , R C ) \); a visit in breadth gives the distances in moves (Lemma 1), which are the costs of the shortest paths when the free cells cost the same and the moves are four, and Dijkstra's algorithm the distances of (4) otherwise. The node \( r C + c \) is an int, and hence the grid has at most \( 2^{31} - 1 \) cells; the neighbors of \( u \) are computed from its row and its column before any offset is added, so that no sum leaves \( [ 0 , R C ) \).
The costs of the cells change by setCost(), which tells each change as the event Changed< Value , int , C > through the subject policy of the grid (no code with NoObservers). It keeps \( n \), the least cost \( \gamma_{\mathrm{min}} \) of a free cell and the number \( m \) of the free cells of that cost: taking the cell out and putting it back with its new cost keeps all three in \( O( 1 ) \) time, but when the cell was the last one of the least cost and its new cost is larger, which needs a new count of the grid; the grid is unoriented exactly when \( m = n \). An arc \( ( x , v ) \) exists when \( x \), \( v \) and, for a corner, its sides allow it, and it weighs the cost of \( v \) or of \( x \); hence a change of the cell \( u \) touches only the arcs into \( u \) (the cell entered pays) or out of \( u \) (the cell left pays) when \( u \) stays free, and only arcs whose head is \( u \) or a free cell at a move of \( u \) when it is blocked or freed, since \( u \) is a side of the corners between two of its neighbors. forEachAffected() gives these heads, at most nine, and for a batch the union of its calls on the coalesced events, read after the batch, holds every head of a changed arc: an arc that changed has one of its at most four cells changed, and a case analysis on which one (the cell that pays, an end blocked or freed, or a side) finds an event whose call gives the head. An incremental search (LPA*, D* Lite) thus repairs the right-hand sides of those heads only. The heuristic of the grid reads \( \gamma_{\mathrm{min}} \), which may change; such a search takes a lower bound of the costs that the changes may give instead.
On an unoriented connected graph a spanning tree has \( n - 1 \) edges, and a minimum one has the least total weight. Both algorithms of MinimumSpanningTree.h rest on the property of the cuts (Theorem 14.1 of the book), which reads as follows: if \( A \) is contained in a minimum spanning tree and no edge of \( A \) crosses the cut \( ( S , V \setminus S ) \), then
\[ A \cup \{ e \} \text{ is contained in a minimum spanning tree, } e \text{ a lightest edge across } ( S , V \setminus S ) . \tag{7} \]
Indeed, in a minimum tree that does not contain \( e \) the path between the ends of \( e \) crosses the cut on some edge \( e' \) with \( w( e ) \le w( e' ) \), and swapping \( e' \) for \( e \) gives another spanning tree that is no heavier.
kruskal() takes the edges by increasing weight and keeps one if its ends are in two components of the forest built so far, i.e., if it is a lightest edge across the cut around one of them. The sort costs \( O( m \log n ) \) (or \( O( m + n + k ) \) by counting, with integer weights in \( [ 0 , k ) \)), and with an MFSET with the rank and the compression of the paths the rest costs \( O( m \, \alpha( m , n ) ) \), \( \alpha \) the inverse of the function of Ackermann, which is at most 4 in practice. prim() grows one tree from \( r \), the cut being the tree itself, and keeps the nodes out of it in a priority queue by the weight of their lightest edge to it; this gives the same three bounds as the shortest paths (\( O( n^2 ) \), \( O( m \log n ) \) and \( O( m + n \log n ) \)), the list being usually preferable on the dense graphs. Dually, a spanning forest is minimum if and only if no edge out of it weighs less than the heaviest edge of the path of the forest between its ends (the property of the cycles), and isMinimumSpanningForest() checks it in \( O( m n ) \).
A network has a source \( s \), a sink \( t \) and a capacity \( c( u , v ) \ge 0 \) on each edge; a flow satisfies \( 0 \le f( u , v ) \le c( u , v ) \) and is conserved at every node but \( s \) and \( t \), and its value \( | f | \) is the net flow out of \( s \). FlowNetwork of MaxFlow.h keeps for each edge a twin in the opposite direction, with \( f( v , u ) = - f( u , v ) \), so that the residual network, made of the edges with \( c_f( u , v ) > 0 \), is at hand.
Theorem 7 (maximum flow, minimum cut). The following are equivalent: (i) \( f \) is a maximum flow; (ii) the residual network has no path from \( s \) to \( t \) (an augmenting path); (iii) \( | f | = c( S , V \setminus S ) \) for some cut with \( s \in S \) and \( t \notin S \) (Theorem 15.1 of the book).
A flow is bounded by the capacity of any cut, and hence (iii) gives (i); (i) gives (ii), since an augmenting path would increase the flow by its least residual capacity. For (ii) to (iii), the nodes \( S \) reachable from \( s \) in the residual network give a cut whose edges are saturated and whose reverse edges carry no flow (minCut()).
The algorithms augment along augmenting paths until (ii) holds, and differ in the path chosen. With integer capacities each augmentation adds at least 1; hence any path (FORD_FULKERSON, by a visit in depth) gives \( O( ( n + m ) | f^* | ) \), a bound that depends on the values of the capacities and may be poor when they are large with respect to \( n \) and \( m \). A shortest path in edges (EDMONDS_KARP, by a visit in breadth) never decreases the distances of the residual network. Each edge is then the critical edge of an augmentation at most \( n / 2 \) times, since between two such times the distance of its tail grows by 2; there are therefore \( O( n m ) \) augmentations of \( O( m ) \) each, i.e., \( O( n m^2 ) \). DINIC sends at once a blocking flow along all the shortest paths of the levels of a visit in breadth, and each such phase increases the distance of \( t \). At most \( n \) phases of \( O( n m ) \) give \( O( n^2 m ) \), and the bound falls to \( O( m \sqrt{n} ) \) on the networks of unit capacities (Even and Tarjan), e.g., those of the bipartite matching; in practice the phases are usually far fewer than \( n \).
The push-relabel of Goldberg and Tarjan (PUSH_RELABEL, beyond the book, in PushRelabel.h) gives up the conservation while it runs: it keeps a preflow, in which each node but \( s \) has an excess \( e( v ) \ge 0 \) of entering flow over leaving flow, and a label \( d( v ) \) with \( d( t ) = 0 \) and \( d( u ) \le d( v ) + 1 \) on every edge with \( c_f( u , v ) > 0 \), so that \( d( v ) \) is a lower bound of the distance in edges from \( v \) to \( t \) in the residual network. It starts by saturating the edges that leave \( s \), and then a node \( u \) with an excess either pushes it on an edge with \( c_f( u , v ) > 0 \) and \( d( v ) = d( u ) - 1 \), or, if there is none, raises \( d( u ) \) to the least \( d( v ) + 1 \) over its residual edges, which keeps the labels valid. A label never decreases and stays below \( 2 n \), since a node with an excess has a residual path back to \( s \); hence there are \( O( n^2 ) \) relabelings and \( O( n m ) \) pushes that saturate their edge, and taking the node of the highest label bounds the others by \( O( n^2 \sqrt{m} ) \) (Cheriyan and Maheshwari). When no node with an excess has a label below \( n \) the preflow is maximum, since a residual path from \( s \) to \( t \) would descend from \( d( s ) = n \) to \( 0 \) by at most 1 per edge in fewer than \( n \) edges; the excesses left are then sent back to \( s \) by the same pushes with the labels of the distances from \( s \). The bound says little of the speed, which comes from two heuristics of Cherkassky and Goldberg: the global relabeling, a visit in breadth backwards from \( t \) that sets each label to its distance, every \( O( n + m ) \) work of the relabelings; and the gap, which, when no node is left with some label \( k \), puts out of the game every node of label above \( k \), since none of them reaches \( t \) any longer. Three choices matter as much on the sparse networks, where the work is mostly the first labeling: each labeling stops after the level of the last node with an excess, the nodes not reached getting the next level but one, still a lower bound of their distance (the lazy update of the HIPR of Cherkassky and Goldberg, in its version 4); the second phase labels only the nodes left at the top, the side of \( s \) of the cut, as the Preflow of LEMON does; and a node scans its edges once, pushing to the lower neighbors and taking the least label of the others, which is its new label if an excess is left. The first labeling takes a node by a conditional write instead of a branch, its tests on the labels and on the residual capacities being hard to predict. FlowNetwork adds a layout for the visits: the head of each edge is stored next to its number in the list of its tail, and the residual capacities in an array of their own, so that a visit reads 8 bytes of an edge, and none of an edge whose head it has already labeled.
Every way above starts from the flow there is. When a capacity falls below the flow of its edge \( ( u , v ) \), FlowNetwork::setCapacity() cuts the flow to the new capacity and leaves an excess at \( u \) and a deficit at \( v \) of the difference (the reparametrization of the dynamic cuts of Kohli and Torr); the next maxFlow() first sends each excess along a residual path to \( s \), to \( t \) or to a deficit, and then fills each deficit from \( s \) or \( t \), both of which give and take any amount. Such paths exist: the flow before the cut decomposes into paths from \( s \) to \( t \) and cycles, and those through \( ( u , v ) \) give, backwards from \( u \) and forwards from \( v \), the residual paths needed. The result is a flow again, from which the maximum is reached by the augmentations or by the push-relabel. The two differ here: the augmenting paths of DINIC start from the flow and stop at the first visit from \( s \) that misses \( t \), which explores the side of \( s \) alone; the push-relabel first makes the same visit when there is a flow, and stops too if \( t \) is not reached, but otherwise it labels the network by a visit from \( t \) before it pushes the excesses, which it takes where setCapacity() left them. Both repair a change for less than a computation from scratch, and on a large network with few paths to find DINIC is usually the cheaper; MaxFlowObserver takes it unless told otherwise.
The flow found is integral when the capacities are (the integrality theorem), and this makes three reductions exact. The edge-disjoint paths of edgeDisjointPaths() of FlowApplications.h are as many as the maximum flow with unit capacities (the theorem of Menger). The b-matching of bipartiteBMatching() of Matching.h is a maximum flow from a source joined to the left side to a sink joined from the right one. Finally, a circulation with lower bounds (feasibleCirculation()) exists if and only if, after the lower bounds are sent, a maximum flow from a new source to a new sink balances the excess left at each node.
A matching of a graph that is not bipartite is beyond the flows: a network has no orientation that turns its paths into the alternating paths of a general graph. Let \( M \) be a matching; a node is free if no edge of \( M \) touches it, and a path is alternating if its edges are in turn out of \( M \) and in it, augmenting if it is alternating and joins two free nodes; its symmetric difference with \( M \) is a matching with one edge more.
Lemma 8 (Berge). A matching is of largest size if and only if no path augments it.
Indeed, if \( | M' | > | M | \), the symmetric difference of the two is made of paths and of even cycles in which the edges of \( M \) and of \( M' \) alternate, and one of its paths has more edges of \( M' \) than of \( M \): it augments \( M \).
A search for such a path from a free node \( r \) grows an alternating tree: the nodes at an even distance from \( r \) along the tree are even, the others odd, each odd node having its mate as its only child. An edge from an even node to a free node not in the tree ends an augmenting path, and one to a matched node not in the tree adds it and its mate; an edge between two even nodes closes an odd cycle, a blossom, whose node nearest to \( r \), its base, is even and is the only node of the cycle matched outside it, if at all.
Lemma 9 (Edmonds). Let \( G / C \) be the graph in which the blossom \( C \) is shrunk to one node, and \( M / C \) the matching left. Then \( M \) has an augmenting path in \( G \) if and only if \( M / C \) has one in \( G / C \).
Indeed, a path of \( G / C \) through the shrunk node enters it by an edge to some node of \( C \), and goes on from the base: one of the two ways around the cycle from that node to the base has an even number of edges and alternates, and lifts the path to \( G \). Conversely, an augmenting path of \( G \) either misses \( C \) or can be cut at its first node in \( C \) after the stem from \( r \) to the base is exchanged with the matching, which keeps the sizes and makes the base free; the part before the cut is then augmenting in \( G / C \).
So the search shrinks each blossom it closes, every node of the cycle becoming even (the odd ones are then searched too), and stops at the first augmenting path, which it lifts through the blossoms, or with a tree in which every edge from an even node goes to an odd one. Such a tree is Hungarian: no augmenting path can ever use its nodes, since its odd nodes cover all the edges of its even nodes, and so they are left out of every later search, a free root that failed never being reached again. maxCardinalityMatching() of BlossomMatching.h keeps the blossoms as the sets of a union-find with the union by rank and the halving of the paths, the representative of a set storing its base; the base common to two even nodes is found by walking from both toward the root one step at a time, which costs no more than twice the cycle shrunk. For each odd node that a blossom makes even it records the edge \( ( a , b ) \) that closed the blossom, its own side first, as the labels of Gabow do: the path from such a node to the root goes back along the path of \( a \) down to \( a \) and then follows that of \( b \), and the augmentation rematches the two parts in turn, each stopping at the node whose mate it has changed already. A search examines each edge of its tree at most twice and merges each node once, i.e., it costs \( O( m \, \alpha( m , n ) ) \) besides the walks, which are paid by the merges; at most \( n / 2 \) searches succeed and each node is the root of at most one that fails, so that the whole costs \( O( n m \, \alpha( m , n ) ) \), i.e., \( O( n m ) \) for every practical \( n \) and within the \( O( n^3 ) \) of the implementation of Gabow. Gabow and Tarjan remove the factor \( \alpha \) with a union-find for the trees of the search, and Micali and Vazirani reach \( O( m \sqrt{n} ) \) by augmenting along a maximal set of the shortest disjoint paths at once, as Hopcroft and Karp do on bipartite graphs, at the price of a much more delicate search.
With a weight \( w( e ) \) on each edge, a matching of largest total weight is a linear program over the matchings, whose polytope Edmonds described: the vectors \( x \ge 0 \) with \( x( \delta( v ) ) \le 1 \) at each node and \( x( E( B ) ) \le ( | B | - 1 ) / 2 \) on each set \( B \) of an odd number of nodes. Its dual has a variable \( y_v \ge 0 \) per node and \( z_B \ge 0 \) per odd set, and asks
\[ \pi( e ) = y_u + y_v - 2 w( e ) + 2 \sum_{B \ni u , v} z_B \ge 0 \quad \forall e = [ u , v ] \in E , \]
with the duals doubled so that integer weights keep them integer.
Theorem 10 (Edmonds). A matching \( M \) is of largest weight if there are duals as above such that (i) \( \pi( e ) = 0 \) on every edge of \( M \), (ii) \( y_v = 0 \) at every free node, and (iii) every odd set with \( z_B > 0 \) holds \( ( | B | - 1 ) / 2 \) edges of \( M \).
Indeed, the conditions are the complementary slackness of the two programs: for any matching \( M' \), summing \( \pi( e ) \ge 0 \) over its edges gives \( 2 w( M' ) \le \sum_v y_v + \sum_B z_B ( | B | - 1 ) \), a bound that (i), (ii) and (iii) turn into an equality for \( M \). Among the matchings of largest size, condition (ii) is dropped and the \( y_v \) may be shifted by a constant, the free nodes having the least dual.
maxWeightMatching() of BlossomMatching.h keeps the three conditions but (ii), which it approaches: every \( y_v \) starts at the largest weight and the matching empty, and the free nodes, whose duals are always equal and the least, are the roots of the trees grown on the edges of slack 0 alone, the blossoms with \( z_B > 0 \) being the odd sets of (iii). When no tight edge extends a tree, the duals change by \( \delta \): down on the outer nodes \( S \) and up on the inner ones \( T \), up on the outer blossoms and down on the inner ones, which keeps the slack of every edge of a tree, and \( \delta \) is the least of the free duals (then (ii) holds and the matching is optimal), of the slacks from \( S \) to a node out of the trees, of half the slacks between two outer blossoms, and of the duals of the inner blossoms, one of which is then expanded. Each change thus makes an edge tight or a blossom expandable, and a stage, which ends at the first augmentation, has \( O( n ) \) of them, since every event of the four kinds either grows the trees, or shrinks or expands a blossom, all of which happen \( O( n ) \) times before an augmentation. The least slack toward each outer blossom is kept per blossom and merged when blossoms are shrunk, so that a change of the duals costs \( O( n ) \), and a stage \( O( n^2 + m ) \); with at most \( n / 2 \) augmentations, the whole costs \( O( n^3 ) \), the bound of Gabow and Lawler that Galil surveys. With integer weights the slack between two outer nodes is even, so that \( \delta \) stays integer, and at the end the duals certify the optimum by Theorem 10, which the audits check. Gabow reaches \( O( n m + n^2 \log n ) \) with mergeable heaps of the slacks and the nearest common ancestors of the blossoms, a structure whose constants pay off only on large sparse graphs.
A trail is a path that uses each edge exactly once, and an Eulerian cycle a closed trail. Let the excess \( x( u ) \) of a node of an oriented graph be the number of the edges leaving it minus that of the edges entering it, and call a node of an unoriented graph odd when its degree is.
Lemma 11 (Euler). Let the edges of \( G \) lie in one component, the orientation ignored. An oriented \( G \) has an Eulerian cycle if and only if \( x( u ) = 0 \) for every node, and an open trail if and only if one node \( s \) has \( x( s ) = 1 \), one node \( t \) has \( x( t ) = - 1 \) and the others have excess 0, the trail going from \( s \) to \( t \); an unoriented \( G \) has an Eulerian cycle if and only if no node is odd, and an open trail if and only if exactly two nodes are odd, the trail joining them. Without the connection, there is no trail.
Indeed, a trail enters and leaves each node it passes through, which gives the conditions; and, under them, a walk along unused edges from \( s \) (from any node with an edge, if all are balanced) can stop only at \( t \) (at its start), since every other node it enters has an unused edge to leave by. The algorithm of Hierholzer (eulerianTrail() and eulerianCycle() of EulerianCycle.h) keeps the walk on a stack: a node with an unused edge pushes its other end, and a node with none is popped and written, so that the closed walks found from the nodes of the walk are spliced into it, and the trail comes out backwards. Each edge is followed once, and a cursor per node never goes back; an unoriented edge is listed at both its ends with one mark of use, the cursor skipping the edges used from the other end, so that the walk costs \( O( n + m ) \). The walk uses every edge reachable from its start, and, under the conditions on the excesses, all of them when they lie in one component, since a balanced component is strongly connected (with the edge \( ( t , s ) \) added in the open case); a walk of fewer than \( m \) edges thus tells that the edges are not connected, which needs no other visit.
Several other headers decide properties by the visits above, with the bound of a visit unless their comments say otherwise. A free tree has \( m = n - 1 \) edges and one component (isTree()). A graph is bipartite if and only if it has no odd cycle (the theorem of Koenig), i.e., if and only if no edge of a visit in breadth joins two nodes of levels of the same parity (twoColoring()). In a free tree the node farthest from any node ends a longest path, and the node farthest from it ends the other (the double sweep of treeDiameter()). The triangles are counted in \( O( m \sqrt{m} ) \) by orienting each edge toward the end of larger degree, which leaves each node with \( O( \sqrt{m} ) \) out-neighbors (countTriangles()). Finally, the algorithm of Johnson lists the simple cycles through a node in \( O( ( n + m ) ( c + 1 ) ) \) for \( c \) cycles (simpleCycles() of Paths.h), since it keeps the search from entering a branch with no cycle at its end; the backtracking of chapter 16 may instead spend exponential time between two cycles.
Beyond the book, Observable.h wraps a graph of any model and turns each of its changes into an event, i.e., the insertion or the deletion of a node, the insertion or the deletion of an edge with its weight, or the change of a weight from \( w_0 \) to \( w_1 \), which it sends to the observers attached to it, each of them with a mask \( M_o \) of the kinds of event that it wants (the pattern Observer of Gamma, Helm, Johnson and Vlissides). With \( M = \bigcup_o M_o \) the union of the masks, a change of kind \( k \notin M \) builds no event at all, and costs what it costs on the graph plus one test; a change that is listened to costs \( O( 1 ) \) per observer that wants it. The changes made inside a batch are collected instead of being sent, and the closing of the batch replaces those on each edge by their net effect: with \( s_0 \) the state of the edge before its first event and \( s_1 \) the state after its last one, both either \( \bot \) (absent) or a weight,
\[ ( s_0 , s_1 ) \mapsto \left\{ \begin{array}{ll} \emptyset & \text{if } s_0 = s_1 , \cr \mathrm{EdgeInserted}( s_1 ) & \text{if } s_0 = \bot \ne s_1 , \cr \mathrm{EdgeDeleted}( s_0 ) & \text{if } s_0 \ne \bot = s_1 , \cr \mathrm{WeightChanged}( s_0 , s_1 ) & \text{otherwise} , \end{array} \right. \tag{8} \]
the weights compared by == when their type has it (never equal otherwise), and a node both inserted and deleted within the batch vanishes with all its edges. The batch is sent as one span, made of the nodes inserted, then of the net events of the edges in the order of their first event, then of the nodes deleted.
Lemma 12 (coalescing). Let \( B \) be the sequence of the events of a batch on a graph \( G \), and \( C \) the sequence that (8) gives. The graph obtained by replaying \( C \) on \( G \) is the one obtained by replaying \( B \), and \( |C| \le |B| \).
Indeed, the state of an edge after \( B \) depends on its last event only, and (8) gives an event that leads from \( s_0 \) to \( s_1 \), or none if the two are equal; the nodes inserted come first, so that every edge of \( C \) finds its ends, and the nodes deleted come last, after the deletions of their edges, which the wrapper sends before the deletion of a node. Each event of \( C \) stands for at least one of \( B \); a hash table on the edges builds \( C \) in \( O( |B| ) \) expected time (coalesce()), and an observer whose mask lacks some kinds of \( C \) gets a filtered copy, in \( O( |C| ) \).
An observer of Reoptimization.h keeps the solution of a problem on the graph together with a certificate of its optimality, i.e., data that prove the solution optimal by conditions that each touch a single edge. It queues the events and works at the next query (the lazy flush): the queue \( Q \) is first coalesced by (8) into \( P \), and if \( |P| > \rho \max( m , 1 ) \), \( \rho \) the ratio of setRecomputeRatio() (\( 1 / 4 \) by default), the solution is computed from scratch, since a repair that touches a large part of the graph costs as much and is slower by a constant. Otherwise each event of \( P \) is tested against the certificate of the previous solution and found harmless, repairable or fatal; the outcome of the query (outcome()) is then from scratch (0) if one event is fatal, by a repair (1) if one is repairable, and by the certificate (2) if all are harmless, in which case nothing is computed.
Lemma 13 (the batch test). If each condition of the certificate involves the weight of a single edge, and each event of \( P \) is tested on the certificate of the solution before \( P \), then the events of \( P \) found harmless leave the solution optimal all together.
Indeed, the events of \( P \) are on distinct edges by Lemma 12, so that each condition of the certificate is touched by at most one of them, and a harmless event keeps true the conditions that it touches; the conditions that no event touches stay as they were.
For the shortest paths from \( r \) (ShortestPathsObserver) the certificate is the tree \( T \) with the distances \( d \), i.e., the reduced costs \( \bar{w}( u , v ) = d[ u ] + w( u , v ) - d[ v ] \), zero on the edges of \( T \) and nonnegative on all the edges by (4). A new weight \( w' \) of an edge \( ( u , v ) \notin T \) with \( d[ u ] + w' \ge d[ v ] \), or the deletion of an edge out of \( T \), is harmless. A new weight with \( d[ u ] + w' < d[ v ] \), or a decrease of an edge of \( T \), is repairable: \( d \) is still the cost of real paths, an upper bound of the distances, and the prototype of section 11.2 started with \( S = \{ u \} \) for the tails \( u \) of all such edges, instead of \( S = \{ r \} \), makes it exact (the algorithm of Ramalingam and Reps for the decreases), in \( O( ( n_\delta + m_\delta ) \log n_\delta ) \) with nonnegative weights, \( n_\delta \) and \( m_\delta \) the nodes whose distance falls and their edges. An increase or the deletion of an edge \( ( u , v ) \) of \( T \) is repairable too, at a higher price: the distances of the nodes of the subtree of \( T \) under \( v \) may grow, and the certificate gives no bound of them, while those of the other nodes are still the costs of their paths in \( T \), which no raised edge touches.
Lemma 14 (the increases). Let \( A \) be the union of the subtrees of \( T \) under the heads of the edges of \( T \) raised or deleted by \( P \). Set \( d[ x ] = \infty \) for \( x \in A \), then
\[ d[ x ] = \min_{( u , x ) \in E} \{ d[ u ] + w( u , x ) \} \quad \forall x \in A , \tag{9} \]
on the weights after \( P \), and run the prototype with \( S \) made of the nodes of \( A \) with \( d[ x ] < \infty \) and of the tails of the edges that violate (4); at the end \( d \) holds the distances after \( P \) and \( T \) is a tree of shortest paths.
Indeed, a node out of \( A \) keeps its path in \( T \), whose edges were not raised, so that \( d \) stays an upper bound of its distance; the nodes of \( A \) get \( \infty \) or, by (9), the cost of a path, again an upper bound. The prototype keeps the upper bounds, and it stops when no edge violates (4): the edges between two nodes out of \( A \) whose weight did not fall satisfied (4) before \( P \) and still do, the edges that enter \( A \) satisfy it after (9), the edges out of the nodes whose \( d \) changes are examined when these leave \( S \), and the lowered ones are in \( S \) by their tails. Hence (4) holds with \( d[ r ] = 0 \), and \( d \) is at most each distance and at least it.
The repair costs the scan of the edges that enter \( A \), which an oriented graph keeps in lists of its own from the first increase on (the graphs of the library give only the edges that leave a node), plus the prototype on the nodes whose distance changes; it is the algorithm of Ramalingam and Reps with the subtree of \( T \) in place of the graph of all the shortest paths, which is the variant that the experiments of Bauer and Wagner on batches of changes found the most robust, since it needs no count of the tight edges and no order among the nodes of \( A \). The subtrees are found by lists of the children of \( T \), updated whenever a parent changes, so that a batch that touches few nodes costs no \( \Theta( n ) \); when \( |A| > n / 2 \) the tree is computed from scratch, which then costs about as much. Only the threshold \( \rho \) of the events and a negative cycle are still fatal.
For the minimum spanning forest \( F \) (SpanningForestObserver) the certificate is the pair of conditions of optimality of section 14.3, i.e., with \( F( u , v ) \) the path of \( F \) between \( u \) and \( v \), the property of the cycles and the property of the cuts (7):
\[ w( f ) \ge \max_{e \in F( u , v )} w( e ) \quad \forall f = [ u , v ] \notin F , \qquad w( e ) \le w( \rho( e ) ) \quad \forall e \in F , \tag{10} \]
\( \rho( e ) \) the replacement of \( e \), the lightest edge out of \( F \) whose path holds \( e \) (the sensitivity analysis of Tarjan). The forest is kept by a link-cut tree (see Dynamic trees), with a node in the middle of each of its edges that carries its weight, so that the maximum of (10) on a path, and the edge that attains it, take \( O( \log n ) \) amortized time, and an edge enters or leaves \( F \) by two links or two cuts, in the same time. The events of \( P \) are applied one at a time, each keeping \( F \) minimum for the graph after it. Raising an edge out of \( F \), lowering one of \( F \) and deleting one out of \( F \) keep (10) and change nothing but a weight. Lowering or inserting an edge \( f = [ u , v ] \) out of \( F \) is harmless if \( w( f ) \) is at least the maximum on \( F( u , v ) \); if it is less, the edge of that maximum leaves and \( f \) enters, by (7) on the cut that the removal of the former leaves; if \( u \) and \( v \) are in two trees, \( f \) enters. Raising or deleting an edge \( e \) of \( F \) splits its tree in two, and the lightest edge between the two parts (\( e \) itself among them, with its new weight, unless deleted) joins them again, by (7); no such edge leaves the forest split (a bridge deleted). That edge is sought by two searches run in turn, a few steps each, the first one that ends giving it: two visits of \( F \) from the ends of \( e \), one node of each in turn, which stop when one of them ends and then scan the edges at the nodes of the smaller part, in time proportional to that part and to its edges; and a scan of the edges out of \( F \) by increasing weight, kept in a balanced tree, the first one whose ends have two distinct roots in the link-cut tree being the answer. With \( s \) the nodes of the smaller part and \( \bar{d} \) their mean degree, the first costs about \( s \bar{d} \), and the second, when the ends of the edges out of \( F \) are spread at random, about \( n / s \) edges of \( O( \log n ) \) each; together, at most twice the cheaper of the two, i.e., about \( \sqrt{ n \bar{d} \log n } \) in that model, though \( \Theta( m ) \) in the worst case (two large parts with no edge between them). A batch with many cuts is joined again at once, instead: the edges raised or deleted leave \( F \), the edges lowered or inserted off \( F \) are set aside, and the trees left are joined by the algorithm of Kruskal on the trees contracted, whose edges are those between two trees, found in the lists of the edges at the nodes out of the largest tree and taken by blocks of the lightest ones (the filter-Kruskal of Osipov, Sanders and Singler); the edges set aside are then taken one at a time, by the cycles. This is correct since the forest so joined is minimum for the graph without the edges set aside (the remaining edges of \( F \) are lightest across the cuts that their removal leaves, as they were), and each edge taken by its cycle afterwards keeps it minimum; the batch costs \( O( n ) \) plus the edges between two trees, against \( O( m \log m ) \) for Kruskal from scratch, and the observer takes it when the cuts times the mean work of its replacements so far exceed \( n \) plus the edges off \( F \). The structures that answer this too in polylogarithmic time (the levels of Holm, de Lichtenberg and Thorup) keep \( O( \log n ) \) copies of the forest, and they lose in practice to the simpler scans on the graphs that are not adversarial (the experiments surveyed by Hanauer, Henzinger and Schulz). Every event costs \( O( \log n ) \) amortized but the raises and the deletions of the edges of \( F \), with no structure built again; the binary lifting that a static forest would use costs \( O( n \log n ) \) at each change of its shape.
For the maximum flow from \( s \) to \( t \) (MaxFlowObserver) the certificate is the side \( S \) of a minimum cut with \( | f | = c( S , V \setminus S ) \), by (iii) of Theorem 7. A new capacity \( c' \) of \( ( u , v ) \) with \( c' \ge f( u , v ) \) is harmless unless \( ( u , v ) \) leaves \( S \) and grows: the flow stays feasible, and the capacity of the cut neither falls below \( | f | \) (an edge of the cut is saturated, so that lowering it below its flow is caught by the other test) nor rises. If \( ( u , v ) \) crosses the cut and grows, the flow is still feasible and the maximum is sought from it, not from zero; if \( c' < f( u , v ) \) the flow is cut to \( c' \), its excess and its deficit are routed as above, and the maximum is sought from the flow so obtained. Only the threshold of the events is fatal.
| Observer | Harmless | Repairable | Fatal |
|---|---|---|---|
| ShortestPathsObserver | off \( T \) with \( d[ u ] + w' \ge d[ v ] \), \( O( 1 ) \) | an improving edge, the prototype from its tail; an edge of \( T \) raised or deleted, (9) on its subtree and the prototype | a subtree of more than \( n / 2 \) nodes |
| SpanningForestObserver | (10) still true, \( O( \log n ) \) | a swap on a cycle, \( O( \log n ) \); an edge of \( F \) raised or deleted, the lightest edge out of the smaller part | more than \( \rho m \) events |
| MaxFlowObserver | \( c' \ge f( u , v ) \) off the cut, \( O( 1 ) \) | an edge of the cut raised, the maximum from \( f \); \( c' < f( u , v ) \), the excess and the deficit routed first | more than \( \rho m \) events |
Beyond the book, Assignment.h solves the assignment problem: \( n \) rows and \( n \) columns, a cost \( c( i , j ) \) for each pair (or none, i.e., \( \infty \)), and a perfect matching of the rows to the columns of least total cost. Its dual gives a potential \( u_i \) to each row and \( v_j \) to each column, and maximizes \( \sum_i u_i + \sum_j v_j \) subject to
\[ \bar{c}( i , j ) = c( i , j ) - u_i - v_j \ge 0 \quad \forall ( i , j ) , \tag{11} \]
the reduced costs; a perfect matching \( M \) whose pairs have \( \bar{c}( i , j ) = 0 \) is then optimal, since its cost is \( \sum_i u_i + \sum_j v_j \), a lower bound of the cost of any perfect matching by (11) (the complementary slackness, as in the Hungarian method of Kuhn). The algorithm of the shortest augmenting paths (Jonker and Volgenant, in the form of Crouse) keeps (11) and the zeros on a partial matching, and adds one row at a time: from a free row \( i_0 \) it finds, by the algorithm of Dijkstra on the reduced costs of the complete bipartite graph (alternating between a column reached and the row matched to it), a shortest path to a free column, of length \( \mu \); it then raises \( u \) and lowers \( v \) along the tree of the search by \( \mu - \delta_j \), \( \delta_j \) the distance of each column \( j \) scanned, which keeps (11) and makes the edges of the path tight, and flips the pairs along the path. On the dense graph a search costs \( O( n^2 ) \), with an array in place of the heap, and \( n \) of them give \( O( n^3 ) \); the potentials start from \( u_i = \min_j c( i , j ) \) and \( v = 0 \), which satisfy (11) whatever the signs of the costs.
Lemma 15 (the change of a row). Let \( ( u , v , M ) \) satisfy (11) with the pairs of \( M \) tight, and let the costs of the row \( i \) change. Removing the pair of \( i \) from \( M \) and setting
\[ u_i = \min_j \{ c( i , j ) - v_j \} \tag{12} \]
gives again a triple that satisfies (11) with the pairs tight, with one free row, so that one augmentation, \( O( n^2 ) \), gives an optimal assignment for the new costs; the same holds for a column \( j \), with \( v_j = \min_i \{ c( i , j ) - u_i \} \), and for any set of rows and columns, one augmentation for each pair removed.
Indeed, (12) makes the reduced costs of the row \( i \) nonnegative, and those of the other rows did not change; the pairs left in \( M \) are outside the row \( i \), so that they stay tight. A column \( j \) is the same with the roles exchanged, and when the rows are set first the minimum of the columns sees their new potentials. This is the incremental assignment of Toroslu and Üçoluk (a row and a column added to a solved problem, solved by one augmentation; Volgenant remarks that it is a step of the method of Jonker and Volgenant) and the dynamic Hungarian algorithm of Mills-Tettey, Stentz and Dias for the costs that change, here with the shortest augmenting path in place of the labels of the Hungarian method. A change of a single cost \( c( i , j ) \) off \( M \) that leaves \( \bar{c}( i , j ) \ge 0 \) (a raise, or a fall that the duals allow) changes nothing, in \( O( 1 ) \); any other frees the row \( i \). With \( k \) rows and columns changed, the repair costs \( O( k n^2 ) \) against the \( O( n^3 ) \) of a solution from scratch, which Assignment::solve() chooses when \( 2 k > n \).
Beyond the book, each observer of Reoptimization.h and the Assignment decide between a repair and a computation from scratch by a recompute policy (ReoptPolicy of Modification.h), an object of their own with three entry points: scratch(), asked before the repair with the net events \( k \) and the size \( s \) of the instance (the edges, or the \( n^2 \) costs of the assignment), abandon(), asked with the work \( w \) of the repair against the work \( \ell \) of a computation from scratch, and record(), told the cause of the outcome afterwards. The work is a count of elementary operations that the observer has at hand (the nodes whose distance is lost, the steps of the replacements of the forest, the rows and the columns freed), never a time, and the policy therefore decides the same on every machine. The default RatioPolicy answers \( k > \rho \max( s , 1 ) \) to the first question and \( w > \alpha \ell \) (or more than \( \beta > 0 \) extractions of one node beyond its first, for the shortest paths) to the second, with \( \rho = 1 / 4 \), \( \alpha = 1 / 2 \) and \( \beta = 0 \) (off); the forest sets \( \alpha = 1 \) in its own object. The calls are the following: the shortest paths ask abandon() with \( w = |A| \), the subtrees lost of Lemma 14, against \( \ell = n \), the nodes that a computation from scratch settles at most, when \( A \) is not empty, and again at each extraction of a node beyond its first; the forest asks it with \( w \) the cuts times the mean work of its replacements so far, against \( \ell = n + |E \setminus F| \), the work of the join of the trees, and on a yes it joins the trees in one pass instead of replacing the cuts one at a time; the assignment asks it with \( w = |D_r| + |D_c| \) against \( \ell = n \); the maximum flow asks only scratch(), and the observer of the assignment asks neither (the events cost it only through the rows and the columns they touch).
Lemma 16 (the default policy). With RatioPolicy and its default values, each observer computes from scratch at the same queries, and repairs or certifies at the others, as with the fixed thresholds of Changes of the graph and reoptimization and The assignment and its reoptimization (\( |P| > \rho \max( m , 1 ) \), \( 2 |A| > n \) for the shortest paths, the cuts times the mean work above \( n + |E \setminus F| \) for the batch of the forest, \( 2 ( |D_r| + |D_c| ) > n \) for the assignment), and therefore it gives the same solutions with the same counts of the outcomes.
Indeed, the first test is the same expression of floating point as before. For the others, \( w > \ell / 2 \) with \( w \) and \( \ell \) integers below \( 2^{53} \) is \( 2 w > \ell \), since \( \ell / 2 \) is exact in floating point, and \( w > 1 \cdot \ell \) is \( w > \ell \). The question of the shortest paths is skipped only when \( A = \emptyset \), where \( 2 |A| > n \) is false anyway, and the question at each extraction beyond the first answers no, since \( \beta = 0 \) switches off its second part and its first part is the test \( 2 |A| > n \) already answered no; the detection of a negative cycle (more than \( n \) extractions) comes before it, as before. At the close of a batch scratch() is asked with closing set, and answers no unless early, so that the subject sends the events as before. The policy keeps no state (record() does nothing), the questions come in the order of the old tests, and the causes refine the outcomes (Reopt::outcomeOf()), so that each count of count() is the one of before. Finally, the periodic sum of the floating total of the forest changes the total only, not the outcomes, and is skipped for exact weights.
Lemma 17 (the fallback). At any query of an observer, and at any point of its repair, computing the solution from scratch in place of the repair gives an optimal solution of the graph of now, whatever the policy answered, and also after a Rebuilt that made it drop its queue.
Indeed, a computation from scratch reads only the graph, or a copy of it brought up to date by the events of the query before the computation, and it overwrites every part of the state that the repair may have touched. The shortest paths compute the tree by the algorithm of the book on the graph, and rebuild the lists of the children of \( T \) and the marks of \( A \) (the counts of the extractions are reset by the repair before it returns, and the lists of the entering edges are dropped, to be built again at their next use). The forest computes Kruskal on its copy of the edges, to which the loop of the query has applied every event of \( P \) before the computation, or, after Rebuilt, on a copy made again from the graph. The maximum flow builds its network again from the graph. The assignment computes from the costs, into which the events of \( P \) were written, or, after Rebuilt, every row read again from the graph. The solution is then optimal by the correctness of the algorithm of the book, and the certificate of the next query is the one of that solution. A policy can therefore only make an observer slower or faster, never wrong: the price of a bad answer is a computation from scratch where a repair would have cost less, or the reverse.
The total weight of the forest is kept by additions and subtractions as the weights of its edges change, and on floating weights it drifts: a plain sum after \( k \) terms has an error of the order of \( k \varepsilon \) times the largest magnitude added (Higham, chapter 4), which an edge raised to \( 10^{17} \) and back makes larger than the total of the other edges. The policy bounds it in two ways: (i) the total is summed again from \( F \) after \( \mathit{period} \cdot |F| \) changes (\( \mathit{period} = 1 \) by default), at an amortized cost of \( O( 1 ) \) per change, so that \( k \) stays of the order of \( |F| \); (ii) with compensated, the sum is that of Neumaier (NeumaierSum), whose error is of the order of \( \varepsilon \) times the sum of the absolute values of the terms, independently of \( k \). At the level of the audits the observer compares its total with the sum over \( F \) within \( 10^{-9} \) times the sum of the absolute weights of \( F \); the default periodic sum may of course fail this test on adversarial magnitudes between two sums, and the audit is there to catch it in the tests.
A batch on a wrapper whose observers listen to every kind is collected whole, and when it holds only changes of edges (insertions, deletions and changes of weights, each with the old value) it can be undone by them.
Lemma 18 (the rollback of a batch). Let a batch collect the events \( e_1 , \ldots , e_k \) of changes of edges only, every kind being listened to. Applying the inverses \( e_k^{-1} , \ldots , e_1^{-1} \) under a mute gives back the weights of every edge (and its absence), and the observers, told nothing, are as before the batch.
Indeed, every change of an edge through the wrapper emits its event, since every kind is wanted, and the batch collects it; the change after \( e_1 , \ldots , e_{i-1} \) is undone by \( e_i^{-1} \), which restores the state of its edge before \( e_i \), and by induction from \( i = k \) down to \( 1 \) every edge gets its state before the batch. The inverses emit nothing under the mute, and the events of the batch are dropped, so that no observer receives anything. The graph is the same up to the order of the edges in its lists, which the algorithms of the observers read only to break ties. A node inserted or deleted has no such inverse (the numbers of the nodes are not reused), and a batch that holds one is sent to the observers instead, as on a structure that cannot be undone; UndoLog undoes in the same way the changes of edges sent outside a batch, through apply(), and forgets its records at a change of a node.
The AdjacencyMatrix and the AdjacencyLists of chapter 12 of Morin's book are MatrixGraph and ListGraph, whose adj( u ) is its outEdges() and inAdj( u ) its inEdges(), the column of \( u \) in \( \Theta( n ) \) on the matrix and a scan of all the lists in \( O( n + m ) \) on the lists. The matrix of incidence of exercise 12.2, \( n \times m \) with \( -1 \) at the source and \( +1 \) at the target of each edge, is IncidenceGraph: kept by columns, it takes \( n m \) bytes, insertEdge() appends a column in \( O( n ) \) amortized, hasEdge( i , j ) reads the row \( i \) and, at each \( -1 \), the entry \( j \), \( O( m ) \), deleteEdge() copies the last column over the one found, \( O( m + n ) \), and adj( i ) and inAdj( i ) search the column of each edge of \( i \) for its other end, \( O( m + n \deg( i ) ) \); no operation beats the other two representations, and its use is the algebra of the graph [see incidence()], not the visits.
Lemma 19 (the universal sink). A universal sink, a node with an edge from each of the other \( n - 1 \) nodes and no edge out, is found or shown not to exist with at most \( 3 ( n - 1 ) \) calls of hasEdge(), \( O( n ) \) time on the adjacency matrix (exercise 12.10).
Indeed, the test of \( ( c , j ) \) rules out \( c \) if the edge is there, since a sink has no edge out, and \( j \) otherwise, since the sink has an edge from every node: a scan of \( j = 1 , \ldots , n - 1 \) that moves \( c \) to \( j \) at each edge found leaves one candidate, \( n - 1 \) tests, and \( 2 ( n - 1 ) \) more check it (universalSink() of Properties.h, on a matrix or on any graph with hasEdge()).
The other exercises of the chapter are solved by the visits of Visit.h, each in \( O( n + m ) \): an unoriented graph is connected if cc() gives one component, whose numbers are the labels of the components (exercises 12.4 and 12.5); the parents that distance() gives from one node of each component are the edges of a spanning forest, \( n - c \) of them for \( c \) components (exercise 12.6); an oriented graph is strongly connected if scc() gives one component, or if every node is reached from a node \( r \) in \( G \) and in its transpose (exercise 12.7); and the distances of distance() are the lengths of the shortest paths from \( r \), by Lemma 1 (exercise 12.8). The dfs2() of the book pushes all the neighbors of a node when it pops it, so that the last neighbor pushed is visited first: on \( 0 \to 1 \), \( 0 \to 2 \), \( 1 \to 2 \) it visits \( 0 , 2 , 1 \) where the recursion visits \( 0 , 1 , 2 \); dfs() keeps instead on its stack the node and the position in its list of neighbors, which visits them in the order of the recursion (exercise 12.9). Exercises 12.1 and 12.3 are the drawings of the representations and of the visits of figure 12.7.
Beyond the book, the headers of ADS/interop/lemon connect ADS with LEMON (Dezső, Jüttner and Kovács) in both directions, compiled only by a program that includes them with LEMON, ADS_WITH_LEMON defined (the target ADS::LEMON of CMake): a program written on LEMON takes a structure of ADS by the named template parameters of its algorithms, with no other change, and a program written on ADS runs the algorithms of LEMON on its graphs. The algorithms of LEMON take their heap by their traits, with the concept lemon::concepts::Heap, whose protocol has a part that is not in the signatures: the cross-reference map from the items to int belongs to the caller, Dijkstra::init() writes PRE_HEAP into it for every node without calling the heap, and the heap must therefore derive the state of an item from that value alone.
Lemma 20 (the slots of DaryHeap). Let the cross-reference map hold, for an item in the heap, its slot \( s \ge 0 \) in an IndexedDaryHeap of ADS, and PRE_HEAP or POST_HEAP otherwise, with the freed slots kept in a list and taken again before a new one. Then state() is right after any sequence of the operations of the concept and of writes of PRE_HEAP by the caller, and the heap of ADS has at most \( f \) ids, \( f \) the largest number of items in the heap at once.
Indeed, push() writes the slot into the map before the heap of ADS takes it, and pop(), erase() and state( i , st ) write POST_HEAP (or \( st \)) when the slot is freed, so that a nonnegative value is always the slot of an item in the heap; a write of the caller sets a negative value, which state() reads as it is. A new slot is taken only when the list is empty, i.e., when every slot is in use, whence the bound. Each operation costs that of the heap of ADS plus one read of the map, one dependent load more than BinHeap makes, whose map holds the place itself; removing it needs the place of an item to be kept in the map of LEMON by the heap of ADS, a parameter that IndexedDaryHeap does not have.
Lemma 21 (the lazy heap). Let a monotone queue without decrease-key hold copies ( slot , key ), a decrease or an increase push a new copy, a slot be never reused before clear(), and a copy be dropped at the top when its slot left or its key is not the priority of the slot. If every key pushed is not less than the last key popped, top() and prio() give an item of least priority, and a sequence of \( q \) pushes of copies costs at most \( q \) extractions.
Indeed, the live copy of a slot is the last one pushed, whose key is the priority of the slot; any other copy of the slot either has another key or is a duplicate of the live one, dropped once its slot left. The live copies are therefore the items with their priorities, the queue extracts the least key first, and the dropped copies precede it with keys not greater, which the monotone use allows; each copy is extracted once. Dijkstra's algorithm with nonnegative integer lengths satisfies the hypothesis, and pushes each node once, so that the slots are at most \( n \).
The maps of LEMON are observers of the notifier of their graph, attached at their construction under its lock; the DenseMap of ADS is an array by the ids that attaches to nothing, so that \( k \) runs of an algorithm of LEMON on one graph that does not change share no mutable state and run on the threads of an executor of ADS. The LemonTap is the converse observer: an ObserverBase of the notifier whose add(), erase(), build() and clear() become the events of ADS Inserted, Erased, Rebuilt and Cleared, the id of the item being the handle, which keeps the parallel arcs of LEMON apart. The notifier tells an insertion after it and an erasure before it, and it calls its observers from the oldest on add() and build() and from the newest on erase() and clear(), which we read in the code of the notifier and which its header does not state: a tap constructed after the map it reads finds the map grown at add() and the value still there at erase(). An insertion is told with the strong guarantee of emit( e , undo ), so that an observer of ADS that throws leaves those before it as they were, and abLEMON removes the item again; the erasures cannot fail, since LEMON forbids it. The LemonMirror keeps a ListDigraph in step with a graph of ADS, in \( O( 1 ) \) expected time per event, and records the kinds of the events since the last query, so that an algorithm of LEMON with a state of its own knows when it must be built again.
Two solves from scratch are delegated to LEMON when ADS_WITH_LEMON is defined, by its public interface only. maxCardinalityMatching() and maxWeightMatching() copy the graph into a SmartGraph and run MaxMatching and MaxWeightedMatching; the matching of largest weight among those of largest size stays with ADS, since LEMON has none. The solve from scratch of Assignment runs MinCostAssignment of abLEMON, whose potentials \( \pi \) satisfy \( c( i , j ) \ge \pi( b_j ) - \pi( r_i ) \) on every edge, with equality on the matching.
Lemma 22 (the potentials of LEMON). With \( u_i = - \pi( r_i ) \) and \( v_j = \pi( b_j ) \) the reduced costs \( c( i , j ) - u_i - v_j \) of the finite costs are nonnegative and zero on the pairs of the assignment, i.e., \( ( u , v ) \) satisfies (11) with the pairs of the assignment of LEMON tight, the hypothesis of Lemma 15, from which the repairs of ADS go on.
Indeed, \( c( i , j ) - u_i - v_j = c( i , j ) + \pi( r_i ) - \pi( b_j ) \), which is the slack of the inequality of LEMON. The same conversion holds for the potentials of NetworkSimplex on the network of the assignment, whose reduced cost of an arc is \( c + \pi( \mathit{tail} ) - \pi( \mathit{head} ) \), and NetworkSimplexAssignment gives them to Assignment in the same way.
LEMON has no warm start of its minimum cost flows nor of its maximum flow, and ADS writes one into private copies of six of its headers, rewritten at configure time by the rules of ADS/interop/lemon/shim/rewrites.txt, each a line header|anchor|what whose anchor must occur once in the header, and put on the include path before LEMON. NetworkSimplex goes on from the basis of the last run, CostScaling and CycleCanceling from its flow made feasible again, CapacityScaling from its flow and potentials, each with setters of one arc or node in \( O( 1 ) \), and Preflow from a flow repaired as follows.
Lemma 23 (the repair of the deficits). Let \( f \) satisfy the capacities, and let the nodes \( v \ne s \) with more flow out than in be repeatedly taken, the flow of an arc out of \( v \) that carries \( f( a ) > 0 \) lowered by \( \min\{ f( a ) , -e( v ) \} \), \( e( v ) \) the excess of \( v \). With integer values the repair ends after at most \( \sum_a f( a ) \) steps, and it leaves a preflow, i.e., no node but \( s \) with a negative excess, of value at least that of \( f \) less the deficits removed.
Indeed, a node with \( e( v ) < 0 \) has an arc out with positive flow, since its outflow exceeds its inflow \( \ge 0 \); each step lowers the total flow by at least 1, and moves the deficit removed at \( v \) to the head of the arc, so that the excesses of the other nodes do not fall below 0 but by the step that marks them again. A preflow is what the two phases of Goldberg and Tarjan start from, and Preflow::initWarm() hands it to init(). MaxFlowObserver takes its solves from an engine, the concept FlowEngine of Reoptimization.h, the augmentations of ADS by default and PreflowEngine on this warm start; the choice between them waits for the measures of the two. A program must see one rewritten copy of each header of LEMON, since two layouts of one class in one binary violate the one definition rule, which compilers do not diagnose.