题目:分配土地
题目描述
从前有个村庄,村民们喜欢在各种田地上插上小旗子,旗子上标识了各种 不同的只数字。某天集体村民决定将覆盖相同数字的最小矩阵形的土地分配给村里做出巨大贡献的村民,请问此次分配土地,做出贡献的村民种最大会分配多大面积?
输入描述
第-行输入 m 和 n,
·m 代表村子的土地的长
·n代表土地的宽
第二行开始输入地图上的具体标识
输出描述
此次分配士地,做出贡献的村民种最大会分配多大面积
备注
。旗子上的数字为1~500,土地边长不超过500
·未插旗子的士地用0标识
用例1
输入
3 3
101
000
010
输出
9
解释:土地上的旗子为1,其坐标分别为(0,0),(2,1)以及(0,2),为了覆
盖所有旗子,矩阵需要覆盖的横坐标为0和2,纵坐标为0和2,所
以面积为9,即(2-0+1)*(2-0+1)=9
用例2
输入
3 3
102
000
034
输出
1
说明
由于不存在成对的小旗子,故而返回1,即一块土地的面积。
java实现
import java.util.*;public class Test {static class Rect {int minH = Integer.MAX_VALUE;int maxH = Integer.MIN_VALUE;int minL = Integer.MAX_VALUE;int maxL = Integer.MIN_VALUE;private void setRow(int row) {this.minH = Math.min(this.minH, row);this.maxH = Math.max(this.maxH, row);}private void setCol(int col) {this.minL = Math.min(this.minL, col);this.maxL = Math.max(this.maxL, col);}}public static void main(String[] args) {Scanner sc = new Scanner(System.in);int m = sc.nextInt(); // 长(行数)int n = sc.nextInt(); // 宽(列数)HashMap<Integer, Rect> rects = new HashMap<>();for (int i = 0; i < m; i++) {for (int j = 0; j < n; j++) {int num = sc.nextInt();if (num > 0) {rects.putIfAbsent(num, new Rect());rects.get(num).setRow(i);rects.get(num).setCol(j);}}}int maxArea = 0;for (int num : rects.keySet()) {Rect rect = rects.get(num);maxArea =Math.max(maxArea, (rect.maxH - rect.minH + 1) * (rect.maxL - rect.minL + 1));}System.out.println(maxArea);}
}
python实现
import sysclass Test:def __init__(self):self.minRow = sys.maxsizeself.maxRow = -sys.maxsizeself.minCol = sys.maxsizeself.maxCol = -sys.maxsizedef setRow(self, row):self.minRow = min(self.minRow, row)self.maxRow = max(self.maxRow, row)def setCol(self, col):self.minCol = min(self.minCol, col)self.maxCol = max(self.maxCol, col)m, n = map(int, input().split())rs = {}for i in range(m):nums = list(map(int, input().split()))for j in range(n):num = nums[j]if num > 0:rs.setdefault(num, Test())rs[num].setRow(i)rs[num].setCol(j)maxArea = 0
for num in rs:rt = rs[num]maxArea = max(maxArea, (rt.maxRow - rt.minRow + 1) * (rt.maxCol - rt.minCol + 1))print(maxArea)
c++实现
#include <bits/stdc++.h>using namespace std;class Rect {
public:int minH;int maxH;int minL;int maxL;Rect() : minH(INT_MAX), maxH(INT_MIN), minL(INT_MAX), maxL(INT_MIN) {}void setRow(int row) {minH = min(minH, row);maxH = max(maxH, row);}void setCol(int col) {minL = min(minL, col);maxL = max(maxL, col);}
};int main() {int m, n;cin >> m >> n;map<int, Rect> rects;for (int i = 0; i < m; i++) {for (int j = 0; j < n; j++) {int num;cin >> num;if (num > 0) {if(rects.count(num) == 0) {rects[num] = Rect();}rects[num].setRow(i);rects[num].setCol(j);}}}int maxArea = 0;for (auto& p : rects) {Rect rect = p.second;int area = (rect.maxH - rect.minH + 1) * (rect.maxL - rect.minL + 1);maxArea = max(maxArea, area);}cout << maxArea << endl;return 0;
}