Find two rectangles with minimal areas that span all points

You are given n points unsorted in an array. You should find two rectangles that cover all the points, and they should not overlap. The edges of the rectangles must be parallel to the x or y ordinate.

The program should return the minimum area covered by all of these points. The area of ​​the first rectangle + the area of ​​the second rectangle. I tried to solve this problem. I sorted the points along the ordinate, and the first is the leftmost of the first rectangle. When we go through the dots, we find the highest and the lowest. I thought that when the difference between two points in x is the largest, this means that the first point is the rightmost of the first rectangles, and the second point is the leftmost of the second rectangle.

Here is the first example



It should work when the points are indicated as in the first example, however, if this example is second, it does not work. Since this will return something similar, and this is wrong:Wrong answer for my algorithm

This should be correct:

Here is a second example  

Then I thought about sorting twice, just do it a second time on the y-axis, and then compare two complete areas. Areas when points are sorted by x and when points are sorted by y, and the smaller one is the correct answer.

+4
source share
2 answers

, , . x- - , , . .

. - . , :

, .

& ; & ; & ; & ; & ; & ; counterexample

, x y.

  • x.
  • . , y. .
  • , .
  • , . .

. , .

O (n & middot; log n) : - O (n & middot; log n), - O (n). O (n) .

+2

, . , , , .

, n n, , n left1, right1, bottom1, top1, left2, right2, bottom2 top2. O (n ^ 8): , (right1 - left1) (top1 - bottom1) + (right2 - left2) (top2 - bottom2). , < < . , O (n ^ 8).

, X Y . X Y . minX, maxX, minY maxY. , , , .

minx, maxX, minY maxY , 2 ^ 4 = 16 , , . O (n ^ 4): O (n), minX, maxX, minY maxY, O (n ^ 4), 16 minX, maxX, minY maxY .

, . , :

  • Y h 1 <= h <= bottom2
  • Y h 2 <= h <= bottom1
  • x w 1 <= h <= left2
  • x w 2 <= h <= left1

, . , , O (n ^ 4). , , (: ).

. , β„– 1 . n h; n , , . n h, " ". β„–2, . β„– 3 . O (n ^ 2):

  • h = point.y
  • point.y <= h point.y > h.
  • X Y .
  • .
  • , h.
  • , w X .
  • ,

? O (n ^ 2), O (n), h w . . min max X/Y /, . :

n h X , Y h.

, , O (n ^ 2), O (n log n) , , O (n) - . .

O (n ^ 2); Omega (n), . , .

+1

Source: https://habr.com/ru/post/1689446/


All Articles