|
ADS
Algorithms and Data Structures
|
The headers of include/ADS/geometry solve two problems on a finite set of points of the plane and answer two kinds of queries on sets that change. The problems are the convex hull, which section 16.1 of the book treats as an example of backtracking, and the closest pair, which the book does not treat and which is solved here by the divide et impera of chapter 12, by a sweep and by a randomized grid; the queries are those of the intervals that contain a point and of the points in a rectangle, answered by two maps augmented with a summary of each subtree (IntervalTree.h and RangeTree.h, beyond the book). This page collects what the headers take for granted: the notation and the predicate of orientation on which every algorithm rests (see Definitions and notation), and, for each problem and each query, the property on which the correctness of its algorithms rests, the argument behind their bounds and, for the problems, the lower bound that they meet (from The convex hull to Stabbing and range counting on augmented maps). 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 point \( p = ( x_p , y_p ) \) has integer coordinates (Point of ConvexHull.h), and the input is a set \( P \) of \( n \) points, possibly repeated. A set of the plane is convex if it contains the segment between any two of its points, and the convex hull of \( P \) is the smallest convex set that contains it, a polygon whose vertices are points of \( P \); the headers give the vertices in counterclockwise order from the lowest point (the rightmost of the lowest ones), with no vertex strictly inside an edge, so that the hull is unique.
| Symbol | Meaning |
|---|---|
| \( \mathrm{cross}( a , b , c ) \) | the cross product \( ( b - a ) \times ( c - a ) \), positive if \( c \) is to the left of the line from \( a \) to \( b \), negative if to the right, 0 if on it (cross()) |
| \( d( p , q ) \), \( d^2( p , q ) \) | the Euclidean distance of two points and its square (squaredDistance()) |
| \( \delta \) | the least distance of two points found so far by an algorithm of the closest pair |
| \( h \), \( k \) | the number of vertices of the hull, and the number of points that survive a filter before the hull is built |
The orientation of three points is the sign of
\[ \mathrm{cross}( a , b , c ) = ( x_b - x_a ) ( y_c - y_a ) - ( y_b - y_a ) ( x_c - x_a ) , \tag{1} \]
i.e., twice the signed area of the triangle \( a b c \), which is positive when the turn from \( a \) through \( b \) to \( c \) is to the left. On integer coordinates (1) is exact, which makes every decision of the algorithms below exact too: with \( |x| , |y| \le 10^9 \) each factor of (1) is below \( 2^{31} \) in absolute value and the products fit a long long, and the same bound keeps the square of a distance within 63 bits. Two points \( p \) and \( q \) are on the same side of the line through \( p_1 \) and \( p_2 \) (sameSide()) when the two signs of (1) agree, and the angle of a vector is compared without trigonometry either by (1) or by pseudoAngle(), an increasing function of the angle with values in \( [ 0 , 4 ) \) (exercise 16.1).
The algorithms of ConvexHull.h rest on one characterization of the edges, which is the following.
Lemma 1 (the edges of the hull). Two points \( p , q \in P \) are consecutive vertices of the hull in counterclockwise order if and only if
\[ \mathrm{cross}( p , q , r ) \ge 0 \quad \forall r \in P , \tag{2} \]
and no point of \( P \) lies on the line through \( p \) and \( q \) out of the segment \( p q \).
Indeed, the line through \( p \) and \( q \) leaves all of \( P \), and hence its hull, in the closed half-plane on its left, so that the segment \( p q \) is on the boundary of the hull; the second condition makes its ends vertices rather than inner points of a longer edge. Checking (2) for each of the \( n ( n - 1 ) \) ordered pairs costs \( O( n ) \) each, i.e., \( O( n^3 ) \) in all (convexHullBrute()).
The scan of Graham (graham()) avoids the pairs that cannot be edges. The lowest point \( o \) is a vertex, and the other points sorted by angle around it are scanned with a stack \( S \) that keeps the following invariant: after the scan of the \( i \)-th point \( p_i \),
\[ S \text{ holds, from its bottom, the vertices of the hull of } \{ o , p_1 , \ldots , p_i \} \text{ in counterclockwise order} . \tag{3} \]
A new point \( p_{i+1} \) is a vertex of the next hull, since it has the largest angle; a vertex \( t \) on top of \( S \), below which lies \( s \), stays a vertex if and only if the turn from \( s \) through \( t \) to \( p_{i+1} \) is to the left, since otherwise \( t \) lies in the triangle \( o s p_{i+1} \). Popping the vertices that make a turn not to the left, a backtrack on the choices made, restores (3). Each point is pushed once and popped at most once; hence the scan costs \( O( n ) \), and the sort by angle, \( O( n \log n ) \), dominates. Of the points collinear with \( o \) only the farthest is kept, and on a tie of the angle the nearer point comes first, so that no vertex is left strictly inside an edge.
The bound is the best possible for the algorithms that compare: the points \( ( a_i , a_i^2 ) \) lie on a parabola, each one is a vertex of their hull, and the hull gives them in the order of the \( a_i \); hence a hull in \( o( n \log n ) \) would sort \( n \) numbers in \( o( n \log n ) \) on the algebraic decision trees, where sorting costs \( \Omega( n \log n ) \).
The lower bound concerns the worst case, and convexHull() is faster on the usual inputs by two devices. First, the points extreme in the eight directions of the axes and of the diagonals lie on the boundary of the hull (each is a vertex unless a tie leaves it inside an edge), and a point strictly inside their octagon is no vertex; the heuristic of Akl and Toussaint drops it with at most 8 evaluations of (1), and for points uniform in a square the octagon contains all of them but a vanishing fraction, so that \( k = o( n ) \) points survive in expectation (Devroye and Toussaint), whereas in a disk a fraction near \( 1 - 2 \sqrt{2} / \pi \approx 0.1 \) survives. Second, the survivors are sorted by \( x \) and then \( y \) instead of by angle, as keys of 64 bits that sort() sorts in \( O( k \log k ) \), and in \( O( k ) \) when it takes the radix sort; the monotone chain of Andrew then builds the lower and the upper chain of the hull by the scan of Graham from the leftmost point to the rightmost and back, with the same invariant (3) on each chain.
| Function | Algorithm | Time | Source |
|---|---|---|---|
| convexHullBrute() | every segment checked by (2) | \( O( n^3 ) \) | section 16.1 |
| graham() | sort by angle and scan with a stack | \( O( n \log n ) \) | Graham (1972), section 16.1 |
| convexHull() | octagon filter, radix sort, monotone chain | \( O( n + k \log k ) \), \( O( n + k ) \) with the radix sort; \( O( n ) \) expected on points uniform in a square | Akl and Toussaint (1978), Andrew (1979) |
The closest pair of \( P \), \( n \ge 2 \), minimizes \( d( p , q ) \) over the pairs of distinct places, and the comparison of all the pairs costs \( \Theta( n^2 ) \) (closestPairBrute()). The headers compare the squares \( d^2 \), which are integers, so that no root is ever taken.
Lemma 2 (the strip). Let the points be split by a vertical line \( x = x_m \) into two halves whose closest pairs are at distance at least \( \delta \). A pair closer than \( \delta \) that crosses the line has both points in the strip \( | x - x_m | < \delta \), and in the strip sorted by \( y \) each point has at most 7 others within \( \delta \) above it.
Indeed, the points of the strip with ordinate in \( [ y , y + \delta ) \) lie in a \( 2 \delta \times \delta \) rectangle whose two \( \delta \times \delta \) squares, one on each side of the line, hold at most 4 points each, since the four \( \delta / 2 \) squares of each hold at most one point of its half (their diameter is below \( \delta \)).
The divide et impera of closestPair() sorts the points by \( x \) once, solves the two halves recursively, and scans the strip comparing each point with the next ones until their difference in \( y \) reaches \( \delta \), i.e., with \( O( 1 ) \) of them by Lemma 2. The strip is sorted by \( y \) in linear time since each recursive call returns its range sorted by \( y \), and the two ranges are merged as in mergesort; hence
\[ T( n ) = 2 T( n / 2 ) + O( n ) = O( n \log n ) . \tag{4} \]
This is optimal on the algebraic decision trees, since \( n \) numbers are distinct if and only if the closest pair of the points \( ( a_i , 0 ) \) is at a positive distance, and the distinctness of \( n \) numbers costs \( \Omega( n \log n ) \) there.
The randomized algorithms escape the lower bound by the floor function, which the decision trees do not have. In the grid of Golin, Raman, Schwarz and Smid the points are taken in a random order, and the \( i \)-th one is compared with the points of the 9 cells around its own in a grid of side \( \lfloor \delta_i \rfloor + 1 \), \( \delta_i \) the least distance among the points before it; a cell holds \( O( 1 ) \) of those points, since they are at distance at least \( \delta_i \) from one another (the points are shuffled by a generator seeded with \( n \), so that the order is random only as far as the generator is). The grid is rebuilt, in \( O( i ) \), only when the \( i \)-th point lowers the least distance, i.e., when it belongs to the closest pair of the first \( i \) points; over the random order this happens with probability at most \( 2 / i \), since that pair has two points and each of the \( i \) is the last with the same probability (a backward analysis). The expected time is therefore
\[ \sum_{i=2}^{n} \Bigl( O( 1 ) + \frac{2}{i} \, O( i ) \Bigr) = O( n ) , \tag{5} \]
on any input, the expectation being over the random order only.
The sweep of closestPairSweep() exploits the usual inputs instead: the points sorted by \( x \) (by sort(), in \( O( n ) \) when it takes the radix sort, \( O( n \log n ) \) otherwise) are scanned from the left, and each one is compared with the ones before it whose difference in \( x \) is below the current \( \delta \). On points spread in the plane there are \( O( 1 ) \) of them, and the sweep is linear; on inputs that crowd the strip with points far apart in \( y \) it is not, and after \( 16 n \) comparisons the sweep gives up, tries the other axis and, if that fails too, leaves the problem to the grid, whose bound (5) holds on any input.
| Function | Algorithm | Time |
|---|---|---|
| closestPairBrute() | all the pairs | \( \Theta( n^2 ) \) |
| closestPair() | divide et impera, Shamos and Hoey | \( O( n \log n ) \) |
| closestPairSweep() | sweep on a radix sort, then the randomized grid | the sort, plus \( O( n ) \) when the sweep succeeds and \( O( n ) \) expected always |
Both structures are maps balanced by weight whose nodes keep, besides a key and its multiplicity, the value over their subtree of a monoid \( ( \mathcal{A} , \oplus , \mathbf{0} ) \),
\[ \mathit{aug}( u ) = \mathit{aug}( u.\mathit{left} ) \oplus g( \mathit{key}( u ) ) \oplus \mathit{aug}( u.\mathit{right} ) , \tag{6} \]
\( g \) the summary of one key and \( \mathit{aug} = \mathbf{0} \) on the empty tree (the augmented maps of Sun and Blelloch, JoinTree.h, see Augmented maps). Every change of the tree passes through its join, which recomputes (6) on the nodes that it creates or rebalances; hence the augmentation costs one evaluation of \( \oplus \) per node touched, i.e., a constant factor on the bounds of the map when \( \oplus \) costs \( O( 1 ) \), and the cost of \( \oplus \) times the nodes touched otherwise. A range of keys is the disjoint union of \( O( \log n ) \) whole subtrees and single nodes, those that hang from the two paths to its ends, so that the sum of the augmentation over a range is read in \( O( \log n ) \) evaluations of \( \oplus \).
The interval tree (IntervalTree) keeps the closed intervals \( [ a , b ] \) ordered by \( ( a , b ) \), with \( g( a , b ) = b \) and \( \oplus = \max \), the identity being no interval.
Lemma 3 (the stabbing query). An interval of the tree contains \( x \) if and only if
\[ \max\{ b : ( a , b ) \in T ,\ a \le x \} \ge x . \tag{7} \]
Indeed, \( [ a , b ] \) contains \( x \) if and only if \( a \le x \) and \( b \ge x \), and the intervals with \( a \le x \) form a prefix of the order, the keys up to \( ( x , +\infty ) \). The prefix is the union of the left subtrees and of the nodes that the path from the root leaves on its left while it searches for \( ( x , +\infty ) \), and stabbed() reads the maximum of (7) on that path in \( O( \log n ) \). To report the intervals, stab() visits the tree in symmetric order but enters a subtree only if its \( \mathit{aug} \) is at least \( x \), and never goes right of a node with \( a > x \); a subtree entered holds an interval with \( b \ge x \), and either that interval has \( a \le x \) and is reported, or the visit stops at the first node with \( a > x \) on the path to it. Each node visited is thus on the path from the root to a reported interval or to the end of the prefix, and the visit costs \( O( \min( n , ( k + 1 ) \log n ) ) \) for \( k \) intervals reported, against the \( O( \log n + k ) \) of the interval tree of Edelsbrunner and of the priority search tree of McCreight, which are structures built for this query rather than ordered maps.
The range tree (RangeTree) keeps the points ordered by \( ( x , y ) \), with \( g( x , y ) \) the sequence \( ( y ) \) and \( \oplus \) the merge of two sorted sequences, the identity being the empty one; the augmentation of a node is then the sorted ordinates of its subtree, and a point is in the augmentation of each of its \( O( \log n ) \) ancestors, which gives the \( \Theta( n \log n ) \) space of the range tree of Bentley. The points of \( [ x_1 , x_2 ] \times [ y_1 , y_2 ] \) are those of the keys from \( ( x_1 , -\infty ) \) to \( ( x_2 , +\infty ) \) whose ordinate lies in \( [ y_1 , y_2 ] \); the range of the keys is covered by \( O( \log n ) \) pieces, and in each piece two binary searches on its sorted ordinates count the ordinates in \( [ y_1 , y_2 ] \), so that count() costs
\[ O( \log n ) \cdot O( \log n ) = O( \log^2 n ) . \tag{8} \]
The fractional cascading of Lueker and of Willard removes one factor \( \log n \) from (8) with pointers from each sequence into those of the children, which every merge would have to rebuild. The merge is not of constant cost: the construction by joins of balanced halves merges each point once per level, \( O( n \log n ) \) work in all, while one insertion or deletion merges again the sequences of all the ancestors of its point, the root's of \( n \) ordinates included, i.e., \( O( n ) \); the dynamic range tree of Sun and Blelloch keeps \( O( \log^2 n ) \) per update by sharing the inner trees between persistent versions.
| Structure | Augmentation | Query | Update | Space |
|---|---|---|---|---|
| IntervalTree | the largest right end | stabbed() \( O( \log n ) \), stab() \( O( \min( n , ( k + 1 ) \log n ) ) \) | \( O( \log n ) \) | \( \Theta( n ) \) |
| RangeTree | the sorted ordinates | count() \( O( \log^2 n ) \) | \( O( n ) \); \( O( n \log n ) \) to build | \( \Theta( n \log n ) \) |