解题思路
要找到覆盖所有点的最小正方形,我们需要:
- 维护一个边界矩形,记录所有点的范围
- 根据边界矩形计算所需的最小正方形
- 输出正方形的面积
关键点
- 使用Pair或元组存储点的坐标
- 维护边界矩形的四个边界值
- 处理多组测试数据
代码
#include <iostream>
#include <utility>
#include <vector>
#include<climits>
using namespace std;
class SquareCover {
private:
struct Boundary {
int left, right, top, bottom;
Boundary() : left(INT_MAX), right(INT_MIN),
top(INT_MIN), bottom(INT_MAX) {}
void update(int x, int y) {
left = min(left, x);
right = max(right, x);
top = max(top, y);
bottom = min(bottom, y);
}
// 添加const修饰符,表示这个方法不会修改成员变量
int getMinSide() const {
return max(right - left, top - bottom);
}
};
public:
void solve() {
int n;
while (cin >> n) {
Boundary bound;
readPoints(n, bound);
cout << calcArea(bound) << endl;
}
}
private:
void readPoints(int n, Boundary& bound) {
for (int i = 0; i < n; i++) {
int x, y;
cin >> x >> y;
bound.update(x, y);
}
}
long long calcArea(const Boundary& bound) {
long long side = bound.getMinSide();
return side * side;
}
};
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
SquareCover solution;
solution.solve();
return 0;
}
import java.util.*;
import java.io.*;
public class Main {
static class Point {
int x, y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
}
static class BoundingBox {
int left, right, top, bottom;
BoundingBox() {
left = Integer.MAX_VALUE;
right = Integer.MIN_VALUE;
top = Integer.MIN_VALUE;
bottom = Integer.MAX_VALUE;
}
void expandToInclude(Point p) {
left = Math.min(left, p.x);
right = Math.max(right, p.x);
top = Math.max(top, p.y);
bottom = Math.min(bottom, p.y);
}
long getMinSquareArea() {
long side = Math.max(right - left, top - bottom);
return side * side;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
int n = sc.nextInt();
BoundingBox box = new BoundingBox();
for (int i = 0; i < n; i++) {
Point p = new Point(sc.nextInt(), sc.nextInt());
box.expandToInclude(p);
}
System.out.println(box.getMinSquareArea());
}
sc.close();
}
}
from dataclasses import dataclass
from typing import List, Tuple
@dataclass
class BoundingBox:
left: int = float('inf')
right: int = float('-inf')
top: int = float('-inf')
bottom: int = float('inf')
def update(self, x: int, y: int) -> None:
"""更新边界框以包含新的点"""
self.left = min(self.left, x)
self.right = max(self.right, x)
self.top = max(self.top, y)
self.bottom = min(self.bottom, y)
def get_min_square_area(self) -> int:
"""计算最小正方形面积"""
side = max(self.right - self.left, self.top - self.bottom)
return side * side
def solve_test_case() -> int:
"""处理单个测试用例"""
n = int(input())
box = BoundingBox()
for _ in range(n):
x, y = map(int, input().split())
box.update(x, y)
return box.get_min_square_area()
def main():
"""主函数处理多组输入"""
while True:
try:
print(solve_test_case())
except EOFError:
break
if __name__ == "__main__":
main()
算法及复杂度
- 算法:边界框扩展
- 时间复杂度:
,每个点只需处理一次
- 空间复杂度:
,只需存储边界值