POJ - 3494 Largest Submatrix of All 1’s 单调栈求最大子矩阵

Largest Submatrix of All 1’s

Given a m-by-n (0,1)-matrix, of all its submatrices of all 1’s which is the largest? By largest we mean that the submatrix has the most elements.

Input

The input contains multiple test cases. Each test case begins with m and n (1 ≤ mn ≤ 2000) on line. Then come the elements of a (0,1)-matrix in row-major order on mlines each with n numbers. The input ends once EOF is met.

Output

For each test case, output one line containing the number of elements of the largest submatrix of all 1’s. If the given matrix is of all 0’s, output 0.

Sample Input

2 2
0 0
0 0
4 4
0 0 0 0
0 1 1 0
0 1 1 0
0 0 0 0

Sample Output

0
4 很巧妙的方法。把图拆成一行行来做,分别求以每行为底的最大矩形面积,类似lc课后辅导。最后比较出最大值即可。
#include<stdio.h>
#include<stack>
using namespace std; int a[][];
int l[],r[]; int main()
{
int n,m,max,i,j;
while(~scanf("%d%d",&n,&m)){
max=;
for(i=;i<=n;i++){
for(j=;j<=m;j++){
scanf("%d",&a[i][j]);
if(a[i][j]==) a[i][j]+=a[i-][j];
}
}
for(i=;i<=n;i++){
stack<int> s;
for(j=;j<=m;j++){
while(s.size()&&a[i][s.top()]>=a[i][j]) s.pop();
l[j]=s.size()==?:s.top()+;
s.push(j);
}
while(s.size()){
s.pop();
}
for(j=m;j>=;j--){
while(s.size()&&a[i][s.top()]>=a[i][j]) s.pop();
r[j]=s.size()==?m:s.top()-;
s.push(j);
}
for(j=;j<=m;j++){
if(a[i][j]*(r[j]-l[j]+)>max) max=a[i][j]*(r[j]-l[j]+);
}
}
printf("%d\n",max);
}
return ;
}
上一篇:UVa 442 Matrix Chain Multiplication(矩阵链,模拟栈)


下一篇:ACM学习历程——UVA442 Matrix Chain Multiplication(栈)