All-one Matrices

All-one Matrices

单调栈

#include<bits/stdc++.h>
#define maxn 3005
using namespace std;
#define P pair<int,int>
int n,m,ans,H[maxn][maxn],pre[maxn][maxn];
stack<P>st;
int a[maxn][maxn];
char c[maxn];//[maxn];
int main()
{
    scanf("%d%d",&n,&m);
    for(int i=1; i<=n; i++)
    {
        scanf("%s",c+1);
        for(int j=1; j<=m; j++) a[i][j]=c[j]-'0';
    }
    for(int i=1; i<=n; i++)
    {
        // tp=0;
        for(int j=1; j<=m; j++)
        {
            H[i][j]=((a[i][j])?H[i-1][j]+1:0);
            pre[i][j]=pre[i][j-1]+(a[i][j]);
            //cout<<pre[i][j]<<' ';
        }
        pre[i][m+1]=pre[i][m];
        //cout<<endl;
    }
    int x;
    for(int i=1;i<=n;i++){
        while(!st.empty())st.pop();
        for(int j=1;j<=m+1;j++){
                x=j;
            while(!st.empty()&&st.top().first>H[i][j]){
                if(i==n||(pre[i+1][j-1]-pre[i+1][st.top().second-1])<(j-st.top().second)){
                    ans++;
                }
                x=st.top().second;
                st.pop();
            }
            if((st.empty()||H[i][j]>st.top().first))
            {

                st.push(P(H[i][j],x));///以Hij为高的矩形最长能向左延伸到x
            }
        }
    }
    printf("%d",ans);
}

猜你喜欢

转载自www.cnblogs.com/liulex/p/11362763.html