链接:登录—专业IT笔试面试备考平台_牛客网
来源:牛客网
时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 262144K,其他语言524288K
64bit IO Format: %lld
Given a N×MN×M binary matrix. Please output the size of second large rectangle containing all "1""1".
Containing all "1""1" means that the entries of the rectangle are all "1""1".
A rectangle can be defined as four integers x1,y1,x2,y2x1,y1,x2,y2 where 1≤x1≤x2≤N1≤x1≤x2≤N and 1≤y1≤y2≤M1≤y1≤y2≤M. Then, the rectangle is composed of all the cell (x, y) where x1≤x≤x2x1≤x≤x2and y1≤y≤y2y1≤y≤y2. If all of the cell in the rectangle is "1""1", this is a valid rectangle.
Please find out the size of the second largest rectangle, two rectangles are different if exists a cell belonged to one of them but not belonged to the other.
输入描述:The first line of input contains two space-separated integers N and M.
Following N lines each contains M characters cijcij.
1≤N,M≤10001≤N,M≤1000
N×M≥2N×M≥2
cij∈"01"
Output one line containing an integer representing the answer. If there are less than 2 rectangles containning all "1""1", output "0""0".
示例1
输入1 2
01
输出
0
示例2
输入1 3
101
输出
1
题意
N×M二进制矩阵。找出第二大矩形的大小,如果存在一个单元格属于其中一个而不属于另一个,则两个矩形是不同的。如果矩形中的所有单元格是“1”,则这是一个有效的矩形。输出第二大的有效矩阵面积。
PS:由样例可得,如果有两个及以上个最大矩阵,输出第二大矩阵也是最大矩阵的值。
题解用二维数组 a[i][j]存矩阵每一个元素可以往上延伸(前提是上方为1)的长度(当前列的长度l)
以下为代码实现:
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= m; j++) {
cin>>c;
if(c== '1') {
a[i][j] = a[i-1][j] + 1;
}
}
}
设置一个横向长度d,纵向长度 l,面积s
a[i][j]!=0时,可继续叠加。d每次加1, 即向右平移一个单位,纵向长度改变,而取较小值才可保证形成有效矩阵。往右递归,便可求出最大面积
AC代码#include
#include
#include
#include
#include
#include
#include
#include
#define ll long long
#define maxn 1005
#define mod 1e9 + 7
using namespace std;
int a[maxn][maxn];
int main() {
int n, m,d,l,s,max1 = 0, max2= 0;
cin>>n>>m;
char c;
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= m; j++) {
cin>>c;
if(c== '1') {
a[i][j] = a[i-1][j] + 1;//当前列的长度l
}
}
}
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= m; j++) {
d=1;//横向
l=a[i][j];//纵向
while(l){
s = l*d;//面积
if(s >max1){
max2 = max1;
max1 = s;
}
else if(s >max2){
max2 =s;
}//递归求Smax
l = min(l, a[i][j+d]);//左右平移后,纵向长度需取最小才可保证形成矩阵
d++;
}
}
}
cout<
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)