题目背景:在一块土地上插1-500数字旗帜,用最小的矩形土地包含相同数字的旗帜,最终输出一块面积最大的矩形面积。
样例1:
输入:
5 5
1 0 1 0 0
0 1 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 2
输出 6
输入
5 5
1 0 1 0 0
0 1 0 0 0
0 0 2 0 0
0 0 0 0 0
0 0 0 0 2
输出 9
解释:对于1旗帜,需要的最小土地面积为6,对于2旗帜,需要的最小土地面积为9,最终输出为9
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
using namespace std;
//计算数字为n的面积函数
int get_s(vector<vector<int>> arr,int r,int l,int n){
//统计数字的最大行列以及最小行列,计算面积
int min_row = 500;//最大行坐标,最大下标为500
int min_col = 500;//最大列坐标
int max_row = -1;
int max_col = -1;
for(int i = 0;i<r;i++){
for(int j = 0;j<l;j++){
if(arr[i][j] == n){//相同,记录其最大最小行列坐标
if(max_row<i){
max_row = i;
}
if(max_col<j){
max_col = j;
}
if(min_row>i){
min_row = i;
}
if(min_col>j){
min_col = j;
}
}
}
}
int size = (max_row-min_row+1)*(max_col-min_col+1);
return size;
}
int main(){
int r,l;
cin >> r >> l;//读取行和列
vector<vector<int>> arr(r,vector<int> (l,0));//二维数组
vector<int> num(501,0);//统计各个数字出现的次数,1-500
int temp = 0;
for(int i = 0;i<r;i++){
for(int j = 0;j<l;j++){
cin >> temp;
arr[i][j] = temp;
num[temp]++;//次数+1
}
}
int max_size = 0;
int size = 0;
for(int i = 1;i<num.size();i++){//从1开始
if(num[i]>1){
size = get_s(arr,r,l,i);
}
if(size > max_size){
max_size = size;
}
}
cout << max_size << endl;
}