When a solution exists (see my comment, giving an example copy where it is absent), it can be found by finding the minimum weight match in a complete bipartite graph that contains a (red or black) vertex for each point, and for each red vertex u and of a black vertex v is an edge (u, v) of weight equal to the Euclidean distance between their corresponding points. This can be optimally solved over time O (V ^ 4).
Why does it work? The basic idea that I took from David Eisenstat, answering a similar question , is that whenever we have a pair of segments of the AB and CD lines that intersect at some point X, Trialgle Inequality can be used to show that the choice of any endpoint of each and their replacement gives a pair of line segments with a smaller or equal total length:
A |\ | \ | \ X C---+-----D \ / \ / B AX + XC >= AC (tri. ineq.) BX + XD >= BD (tri. ineq.) AX + XC + BX + XD >= AC + BD (sum both sides) (AX + BX) + (XC + XD) >= AC + BD (rearrange LHS) AB + CD >= AC + BD (combine pairs of segments on LHS)
Assuming further that the triangles AXC and BXC are non-degenerate, >= becomes a > . (A sufficient condition for this is that none of the three points containing at least 1 red and 1 black point is collinear.) Thus, for any given solution (assigning red nodes to black nodes), if this solution contains the intersection, then its total sum of the lengths of the line segments can be reduced by a nonzero amount by replacing the red (or black) endpoints of the two segments of the line of intersection.
In other words,
Solution contains a crossing => sum of segment lengths is not minimal.
Taking the opposite, we immediately get
Sum of segment lengths is minimal => solution contains no crossing.
Since the minimum weight matching algorithm returns the solution of the minimum possible weight, this establishes its correctness.
(Note that there is no need to worry about whether replacing the endpoints really ensures that the new pair of segments of the AC and BD line does not intersect - although it seems obvious that they will not, we all really need to prove the correctness is to show that crossing exists => sum not minimal .)
j_random_hacker
source share