POJ - 3494 Largest Submatrix of All 1's (seeking the maximum full stack monotone sub-matrix)

链接POJ - 3494 Largest Submatrix of All 1’s

The meaning of problems

Gives a n × m n\times m 1 n , m 2000 1 \ n, m \ 2000 ) of the matrix 01, are all seeking the largest of the sub-matrix 1, the output of the area (unit length of the matrix 1 is provided).



analysis

Here Insert Picture Description
Each considered row , can be regarded as a histogram , above, is then transformed into the largest rectangular area seeking a histogram , which may be utilized monotone stack to handle, stack monotone O ( m ) Man) within a processing timeof all the elements on the left / right of the first large / smaller than the position of the element.

Before monotone stack processing, it requires the need to "column height" of each position , in fact, only need to traverse each column , and then from top to bottom are numbered to.

The total time complexity is O ( n m ) O(n\cdot m)


Code

#include<iostream>
#include<cstdio>
#include<stack>
#include<algorithm>
using namespace std;
typedef long long LL;
typedef pair<int,int> PII;
const int INF=0x3f3f3f3f;
const int maxn=2e3+10;
int n,m,a[maxn][maxn];
int L[maxn],R[maxn];
void prework(int i)    //预处理第i行
{
    stack<int> st;
    for(int j=1;j<=m;j++)
    {
        while(!st.empty()&&a[i][st.top()]>=a[i][j])
            st.pop();
        if(!st.empty())
            L[j]=st.top();     //a[i][j]左边第一个比其小的元素的下标
        else
            L[j]=0;
        st.push(j);
    }
    while(!st.empty())
        st.pop();
    for(int j=m;j>=1;j--)
    {
        while(!st.empty()&&a[i][st.top()]>=a[i][j])
            st.pop();
        if(!st.empty())
            R[j]=st.top();      //a[i][j]右边第一个比其小的元素的下标
        else
            R[j]=m+1;
        st.push(j);
    }
}
int main()
{
    while(~scanf("%d %d",&n,&m))
    {
        for(int i=1;i<=n;i++)
            for(int j=1;j<=m;j++)
                scanf("%d",&a[i][j]);
        for(int j=1;j<=m;j++)     //得出每个位置的”柱高”
        {
            for(int i=1,cnt=0;i<=n;i++)
            {
                if(a[i][j])
                    a[i][j]=++cnt;
                else
                    cnt=0;
            }
        }
        int ans=0;
        for(int i=1;i<=n;i++)
        {
            prework(i);
            for(int j=1;j<=m;j++)
                ans=max(ans,a[i][j]*(R[j]-L[j]-1));
        }
        printf("%d\n",ans);
    }
    return 0;
}

Published 215 original articles · won praise 40 · views 20000 +

Guess you like

Origin blog.csdn.net/Ratina/article/details/104105417