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.


Input
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.


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

题意:给出一个仅含0、1的矩阵,求出其中由1构成的最大矩形面积。

以每一行为底,向上找高,求出每一行所能找的的最大矩形面积,遍历每行之后得到结果

#include
#include
using namespace std;
const int M = 2005;
int mm[M][M];
int h[M][M];
long long ans;
stack s;
int n,m;
long long f(int x)
{
    int L[m+1],R[m+1];
    while(!s.empty())
        s.pop();
    for(int i=0;i<=m;i++)
    {
        while(!s.empty()&&h[x][i]<=h[x][s.top()])
            s.pop();
        if(s.empty())
            L[i] = 1;
        else
            L[i] = s.top()+1;
        s.push(i);
    }
    while(!s.empty())
        s.pop();
    for(int i=m;i>=1;i--)
    {
        while(!s.empty()&&h[x][i]<=h[x][s.top()])
            s.pop();
        if(s.empty())
            R[i] = m;
        else
            R[i] = s.top() - 1;
        s.push(i);
    }
    long long res = -1;
 //   for(int i=1;i<=m;i++)
 //       printf("l = %d\n", L[i]);
    for(int i=1;i<=m;i++)
    {
      //  printf("s = %d\n", (R[i]-L[i]+1)*h[x][i]);
        res = max(res, (long long)(R[i]-L[i]+1)*h[x][i]);
    }
    return res;
}
int main()
{
    while(~scanf("%d%d", &n, &m))
    {
        ans = -1;
        for(int i=1;i<=n;i++)
            for(int j=1;j<=m;j++)
                scanf("%d", &mm[i][j]);
        for(int i=1;i<=m;i++)
        {
            if(mm[1][i])
                h[1][i] = 1;
            else
                h[1][i] = 0;
        }
        for(int j=1;j<=m;j++)
            for(int i=2;i<=n;i++)
            {
                if(mm[i][j])
                    h[i][j] = h[i-1][j] + 1;
                else
                    h[i][j] = 0;
            }//预处理出每个位置的高度
        for(int i=1;i<=n;i++)
            ans = max(ans, f(i));
        printf("%d\n", ans);
    }
    return 0;
}


你可能感兴趣的:(poj 3494 Largest Submatrix of All 1’s(单调栈))