时间限制:C/C++ 1000MS,其他语言 2000MS
内存限制:C/C++ 128MB,其他语言 256MB
难度:困难
描述
从前有个村庄,村民们喜欢在各种田地上插上小旗子,旗子上标识了各种不同的数字。某天集体村民决定将覆盖相同数字的最小矩阵形的土地的分配给为村里做出巨大贡献的村民,请问,此次分配土地,做出贡献的村民中最大会分配多大面积?
备注:旗子上的数字为 1-500,土地边长不超过 500
未插旗子的土地用 0 标识
输入描述
第一行输入 m 和 n,m 代表村子的土地的长,n 代表土地的宽
第二行开始输入地图上的具体标识
输出描述
输出需要分配的土地面积,即包含相同数字旗子的最小矩阵中的最大面积。
用例输入 1 **
3 3
1 0 1
0 0 0
0 1 0
用例输出 1 **
9
提示
土地上的旗子为 1,其坐标分别为(0,0),(2,1)以及(0,2),为了覆盖所有旗子,矩阵需要覆盖的横坐标为 0 和 2,纵坐标为 0 和 2,所以面积为 9,即(2-0+1)*(2-0+1)=9。
#include <iostream>
#include <vector>
#include <unordered_map>
#include <climits>
using namespace std;
int main(){
int m,n;
cin >> m >> n;
vector<vector<int>> grid(m, vector<int>(n, 0));
for(int i = 0; i < m; ++i){
for(int j = 0; j < n; ++j){
cin >> grid[i][j];
}
}
unordered_map<int, vector<pair<int, int>>> num_positions;
for(int i = 0; i < m; ++i){
for(int j = 0; j < n; ++j){
int num = grid[i][j];
if(num != 0){
num_positions[num].emplace_back(i, j);
}
}
}
int max_area = 0;
for(const auto& entry : num_positions){
const auto& positions = entry.second;
int min_row = INT_MAX, max_row = INT_MIN;
int min_col = INT_MAX, max_col = INT_MIN;
for(const auto& pos : positions){
min_row = min(min_row, pos.first);
max_row = max(max_row, pos.first);
min_col = min(min_col, pos.second);
max_col = max(max_col, pos.second);
}
int area = (max_row - min_row + 1) * (max_col - min_col + 1);
if(area > max_area){
max_area = area;
}
}
cout << max_area << endl;
return 0;
}
package main
import (
"fmt"
)
func main() {
var m, n int
fmt.Scan(&m, &n)
grid := make([][]int, m)
for i := range grid {
grid[i] = make([]int, n)
for j := range grid[i] {
fmt.Scan(&grid[i][j])
}
}
numPositions := make(map[int][][2]int)
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
num := grid[i][j]
if num != 0 {
numPositions[num] = append(numPositions[num], [2]int{i, j})
}
}
}
maxArea := 0
for _, positions := range numPositions {
minRow, maxRow := positions[0][0], positions[0][0]
minCol, maxCol := positions[0][1], positions[0][1]
for _, pos := range positions {
if pos[0] < minRow {
minRow = pos[0]
}
if pos[0] > maxRow {
maxRow = pos[0]
}
if pos[1] < minCol {
minCol = pos[1]
}
if pos[1] > maxCol {
maxCol = pos[1]
}
}
area := (maxRow - minRow + 1) * (maxCol - minCol + 1)
if area > maxArea {
maxArea = area
}
}
fmt.Println(maxArea)
}
from collections import defaultdict
m, n = map(int, input().split())
grid = [list(map(int, input().split())) for _ in range(m)]
num_positions = defaultdict(list)
for i in range(m):
for j in range(n):
num = grid[i][j]
if num != 0:
num_positions[num].append((i, j))
max_area = 0
for num in num_positions:
positions = num_positions[num]
min_row = min(p[0] for p in positions)
max_row = max(p[0] for p in positions)
min_col = min(p[1] for p in positions)
max_col = max(p[1] for p in positions)
area = (max_row - min_row + 1) * (max_col - min_col + 1)
if area > max_area:
max_area = area
print(max_area)