Minimum Enclosing Circle
Consider the following problem:
Library Checker - Minimum Enclosing Circle
You're given points .
For each , find whether it lies on the circumference of the minimum enclosing circle of .
Here, by the minimum enclosing circle (MEC) we mean a circle with minimum possible radius that contains all the points, inside the circle or on its boundary. This problem has a simple randomized solution that, on first glance, looks like it would run in , but actually works in expected time.
To better understand the reasoning below, we should immediately note that the solution to the problem is unique:
Why is the MEC unique?
Consider the following setup: Let be the radius of the MEC. We draw a circle of radius around each of the points . Geometrically, the centers of circles that have radius and cover all the points form the intersection of all circles.
Now, if the intersection is just a single point, this already proves that it is unique. Otherwise, the intersection is a shape of non-zero area, so we can reduce by a tiny bit, and still have non-empty intersection, which contradicts the assumption that was the minimum possible radius of the enclosing circle.
With a similar logic, we can also show the uniqueness of the MEC if we additionally demand that it passes through a given specific point or two points and (it is also unique because its radius uniquely defines it).
Alternatively, we can also assume that there are two MECs, and then notice that their intersection (which contains the points already) must have a smaller diameter than initial circles, and thus can be covered with a smaller circle.
Welzl's algorithm
For brevity, let's denote to be the MEC of , and let .
The algorithm, initially proposed by Welzl in 1991, goes as follows:
- Apply a random permutation to the input sequence of points.
- Maintain the current candidate to be the MEC , starting with .
- Iterate over and check if .
- If it means that is the MEC of .
- Otherwise, assign and iterate over and check if .
- If , then is the MEC of among circles that pass through .
- Otherwise, assign and iterate over and check if .
- If , then is the MEC of among circles that pass through and .
- Otherwise, is the MEC of among circles that pass through and .
We can see that each level of nestedness here has an invariant to maintain (that is the MEC among circles that also pass through additionally given , or points), and whenever the inner loop closes, its invariant becomes equivalent to the invariant of the current iteration of its parent loop. This, in turn, ensures the correctness of the algorithm as a whole.
Omitting some technical details, for now, the whole algorithm can be implemented in C++ as follows:
struct point {...};
// Is represented by 2 or 3 points on its circumference
struct mec {...};
bool inside(mec const& C, point p) {
return ...;
}
// Choose some good generator of randomness for the shuffle
mt19937_64 gen(...);
mec enclosing_circle(vector<point> &p) {
int n = p.size();
ranges::shuffle(p, gen);
auto C = mec{p[0], p[1]};
for(int i = 0; i < n; i++) {
if(!inside(C, p[i])) {
C = mec{p[i], p[0]};
for(int j = 0; j < i; j++) {
if(!inside(C, p[j])) {
C = mec{p[i], p[j]};
for(int k = 0; k < j; k++) {
if(!inside(C, p[k])) {
C = mec{p[i], p[j], p[k]};
}
}
}
}
}
}
return C;
}Now, it is to be expected that checking that a point is inside the MEC of or points can be done in (we will discuss this later on). But even then, the algorithm above looks as if it would take in the worst case just because of all the nested loops. So, how come we claimed the linear expected runtime? Let's figure out!
Complexity analysis
For the inner-most loop (over ), clearly its expected runtime is operations. What about the loop over ?
It only triggers the next loop if is on the boundary of the MEC of that also passes through point , and removing would further shrink the circle. Of all points in there can only be at most points with such property, because if there are more than points from on the boundary, it means that after removing any of them, there will still be at least points on the boundary, sufficient to uniquely define the circle.
In other words, after initial random shuffle, there is at most probability that we get one of the at most two unlucky points as . Summing it up over all from to , we get the expected runtime of
In exactly same fashion we can now also prove that the outermost loop has expected runtime of .
Checking that a point is in the MEC of 2 or 3 points
Let's now figure out the implementation detail of point and mec. In this problem, it turns out to be particularly useful to use std::complex as a class for points:
using ftype = int64_t;
using point = complex<ftype>;As a reminder, a complex number is a number of type , where and . In C++, such complex number is represented by a 2-dimensional point . Complex numbers already implement basic component-wise linear operations (addition, multiplication by a real number), but also their multiplication and division carry certain geometric meaning.
Without going in too much detail, we will note the most important property for this particular task: Multiplying two complex numbers adds up their polar angles (counted from counter-clockwise), and taking a conjugate (i.e. changing into ) multiplies the polar angle with . This allows us to formulate some very simple criteria for whether a point is inside the MEC of or specific points.
MEC of 2 points
For points and , their MEC is simply the circle centered at with the radius , in other words the circle that has as a diameter. To check if is inside this circle we simply need to check that the angle between and is not acute.
Inner angles are obtuse, external angles are acute and angles on the circumference are right
Equivalently, we need to check that
doesn't have a positive real coordinate (corresponding to points that have a polar angle between and ).
MEC of 3 points
Adding to the triangle will make it a quadrilateral. Consider the following expression:
In a cyclic quadrilateral, if and are from the same side of , then the angles are equal, and will add up to when summed up signed (i.e. positive if counter-clockwise and negative if clockwise). Correspondingly, if and are on the opposite sides, the angles will add up to .
Adjacent inscribed angles are same, opposing angles complement to 180 degrees
In terms of complex numbers, we can note that is the polar angle of and is the polar angle of . Thus, we can conclude that is the polar angle of
If the angle is or , it means that the imaginary part of is , otherwise we can deduce whether is inside or outside of the enclosing circle of by checking the sign of the imaginary part of . Positive imaginary part corresponds to positive angles, and negative imaginary part corresponds to negative angles.
But which one of them means that is inside or outside of the circle? As we already noticed, having inside the circle generally increases the magnitude of , while having it outside the circle decreases it. As such, we have the following 4 cases:
- , on the same side of as . Then, , and for points inside the circle.
- , on the same side of as . Then, , and for points inside the circle.
- , on the opposite side of to . Then, and for points inside the circle.
- , on the opposite side of to . Then, and for points inside the circle.
In other words, if is positive, points inside the circle will have , otherwise they will have , assuming that we normalize the angles between and . This, in turn, can be checked by the signs of imaginary parts of and .
Note: As we multiply four complex numbers to get , the intermediate coefficients can be as large as , where is the largest coordinate magnitude in the input. On the bright side, if the input is integer, both checks above can be done fully in integers.
Implementation
Now, to actually implement the check, we should first decide how to represent the MEC. As our criteria work with the points directly, a natural and efficient way to do this is to say that MEC is directly represented as a pair or triple of points that defines it:
using mec = variant<
array<point, 2>,
array<point, 3>
>;Now, we can use std::visit to efficiently deal with both cases in accordance with criteria above:
/* I < 0 if z inside C,
I > 0 if z outside C,
I = 0 if z on the circumference of C */
ftype indicator(mec const& C, point z) {
return visit([&](auto &&C) {
point a = C[0], b = C[1];
point I0 = (b - z) * conj(a - z);
if constexpr (size(C) == 2) {
return real(I0);
} else {
point c = C[2];
point I2 = (a - c) * conj(b - c);
point I1 = I0 * I2;
return imag(I2) < 0 ? -imag(I1) : imag(I1);
}
}, C);
}
bool inside(mec const& C, point p) {
return indicator(C, p) <= 0;
}Now, we can finally ensure that everything works by submitting the problem to the Library Checker: #308668.