Use a balanced normalized square tree.
Normalized: collect all x coordinates, sort them and replace them with an index in a sorted array. Same for y coordinates.
Balanced: when building a quad tree, there is always a split in the middle coordinate.
So, when you get the rectangle you want to go, and mark the correct nodes in the tree with some rectangle id. If you find other rectangles at the bottom (which means they will overlap), assemble them in a set. When this is done, if the vector is not empty (you find the overlapping rectangles), then we create a new rectangle to represent the union of the subelements. If the computed rectangle is larger than the one you just inserted, then apply the algorithm again using the new computed rectangle. Repeat this until it grows larger, then move on to the next input rectangle.
For performance, each node in the quad-core storage stores all the rectangles that overlap this node, in addition to marking it as end-node.
Difficulty: initial normalization of O(NlogN) . Inserting and checking for overlaps will be O(log(N)^2) . You need to do this for the original N rectangles, as well as for the ceilings. Each time you detect an overlap, you eliminate at least one of the original rectangles so that you can find the maximum (N-1) overlap. So overall you need 2N operations. So the overall complexity will be O(N(log(N)^2)) .
This is better than other approaches because you do not need to check any rectangles for overlapping.
Sorin
source share