POJ 3494 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.
输入
The input contains multiple test cases. Each test case begins with m and n (1 ≤ m, n ≤ 2000) on line. Then come the elements of a (0,1)-matrix in row-major order on m lines each with n numbers. The input ends once EOF is met.
输出
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.
样例
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
output
0
4
题意
求最大的1矩阵
解题思路
一行一行地做
如果当前列上的数为0则清空
否则累加
如下图:
做到第二行时第一列和第五列就会被清空
单调栈维护列的高度(递增)
当被弹出时求面积
更新答案
代码
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
int n,m,ans,t,q[4020],w[4020],a[2020][2020];
int main()
{
while (scanf("%d%d",&n,&m)!=EOF)
{
memset(w,0,sizeof(w)); //清空
for (int i=1;i<=n;i++)
for (int j=1;j<=m;j++)
scanf("%d",&a[i][j]);
ans=0; //赋初值
w[0]=-1;
w[m+1]=-1; //防止出界
for (int i=1;i<=n;i++)
{
for (int j=1;j<=n;j++)
if (a[i][j]!=0)
w[j]++; //累加
else w[j]=0; //当前的格为0清空
memset(q,0,sizeof(q)); //可要可不要
t=0; //初值呀
for (int k=0;k<=m+1;k++)
{
while (t>0&&w[q[t]]>w[k]) //递增
{
ans=max(ans,w[q[t]]*(k-q[t-1]-1)); //更新答案
t--; //出栈
}
q[++t]=k; //入栈
}
}
printf("%d\n",ans);
}
return 0;
}