Suppose the coordinates of the rectangles are given as follows:
(x_1, y_1) - (x_2, y_2): the first rectangle, where x_1 < x_2 and y_1 < y_2,
(x_3, y_3) - (x_4, y_4): the second rectangle, where x_3 < x_4 and y_3 < y_4
Consider the smallest rectangle that completely covers both original rectangles. Let its opposite corners be (minx, miny) and (maxx, maxy). Then:
minx = min(x_1, x_3), miny = min(y_1, y_3),
maxx = max(x_2, x_4), maxy = max(y_2, y_4)
The dimensions of the covering rectangle are:
length = maxx - minx,
width = maxy - miny
To completely cover both rectangles with a square, the side length of the square must be at least as large as both length and . Therefore, the side length of the minimum square pasture is the maximum of these two values:
Example
Consider two original rectangles:
the first rectangle has its lower-left corner at and its upper-right corner at ,
the second rectangle has its lower-left corner at and its upper-right corner at
Let's calculate the boundaries of the resulting rectangle:
minx = min(6, 1) = 1, miny = min(6, 8) = 6,
maxx = max(8, 4) = 8, maxy = max(8, 9) = 9
The dimensions of the covering rectangle are:
length = 8 - 1 = 7,
width = 9 - 6 = 3
The side length of the covering square is:
Therefore, the area of the minimum covering square is 7^2 = 49.
Algorithm implementation
Initialize the boundaries of the covering rectangle. Since the coordinates are in the range from to , we can set the initial values as follows:
minx = 10; maxx = 0; miny = 10; maxy = 0;Read the coordinates of the two original rectangles. For each rectangle, update the boundaries of the covering rectangle.
for (i = 0; i < 2; i++)
{
scanf("%d %d %d %d", &a1, &b1, &a2, &b2);
if (a1 < minx) minx = a1;
if (a2 > maxx) maxx = a2;
if (b1 < miny) miny = b1;
if (b2 > maxy) maxy = b2;
}Calculate the length and width of the covering rectangle.
l = maxx - minx;
w = maxy - miny;To cover this rectangle with a square, the side length of the square must be at least as large as both its length and its width. Therefore, we choose the larger of the two values.
len = (l > w) ? l : w;Calculate the area of the square and print the answer.
area = len * len;
printf("%d\n", area);