poj 3494 Largest Submatrix of All 1’s

来源:互联网 发布:《网络基础知识》文档 编辑:程序博客网 时间:2024/05/19 17:58

Description

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 m lines 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 20 00 04 40 0 0 00 1 1 00 1 1 00 0 0 0

Sample Output

04

Source

POJ Founder Monthly Contest – 2008.01.31, xfxyjwf


虽然题目是二维的,但是仍然可以转化成单调栈来做。

用一个数组保存每一个0,1值,用另一个数组保存每一行的数的某一列以上所含的连续1的值

再用单调栈的想法就可以顺利解决了


#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>#define MAX_N 2005using namespace std;int a[MAX_N][MAX_N],b[MAX_N][MAX_N];//b数组用来存每一行累计连续1的值int l[MAX_N],r[MAX_N];//每一行的int main(){    int m,n;    while(~scanf("%d%d",&m,&n))    {        memset(b,0,sizeof(b));        for(int i=1;i<=n;i++)        {            for(int j=1;j<=m;j++)            {                scanf("%d",&a[i][j]);                if(a[i][j])                {                    if(b[i-1][j])                        b[i][j]=b[i-1][j]+1;                    else                        b[i][j]=1;                }                else b[i][j]=0;            }        }        int maxn=-1;        for(int i=1;i<=n;i++)        {            l[0]=0,r[n+1]=0;            for(int j=1;j<=m;j++)            {                int k=j-1;                while(k>0&&b[i][j]<=b[i][k]) k=l[k]-1;                l[j]=++k;            }            for(int j=n;j>=0;j--)            {                int k=j+1;                while(k<n+1&&b[i][j]<=b[i][k]) k=r[k]+1;                r[j]=--k;            }            for(int j=1;j<=m;j++)            {                int s=(r[j]-l[j]+1)*b[i][j];                if(s>maxn) maxn=s;            }        }        printf("%d\n",maxn);    }    return 0;}


原创粉丝点击