2019 牛客多校 第八场 A.All-one Matrices(单调栈)

最大全1子矩阵

题意:求极大全1子矩阵的个数

只需要再求最大子矩阵的基础上加个判断当前计算的矩阵是否是极大子矩阵即可。

#include<stdio.h>
#include<iostream>
#include<cstring>
#include<stack>
using namespace std;
#define ls rt<<1
#define rs (rt<<1)+1
#define ll long long
#define fuck(x) cout<<#x<<"     "<<x<<endl;
const int inf=0x3f3f3f3f;
const int maxn=4e3+10;
int d[4][2]= {1,0,-1,0,0,1,0,-1};
int n,m;
int up[maxn],mp[maxn][maxn],pre[maxn][maxn];
stack<int>sta;
int main()
{
    int ans=0;
    scanf("%d%d",&n,&m);
    for(int i=1; i<=n; i++)
        for(int j=1; j<=m; j++){
            char ch;
            scanf(" %c",&ch);
            if(ch=='0')
                mp[i][j]=0;
            else
                mp[i][j]=1;
            pre[i][j]=pre[i][j-1]+(mp[i][j]==1);
        }
    up[0]=up[m+1]=-1;
    for(int i=1; i<=n; i++)
    {
        for (int j=1; j<=m; j++)
            up[j]=(mp[i][j]==0)?0:(up[j]+1);
        while(!sta.empty())
            sta.pop();
        for(int j=0; j<=m+1; j++)
        {
            while(!sta.empty()&&up[sta.top()]>=up[j])
            {
                int tmp=sta.top();
                sta.pop();
                if(up[tmp]==up[j]) continue;
                if(pre[i+1][j-1]-pre[i+1][sta.top()]!=j-1-sta.top()&&up[tmp]) {
                    ans++;
                    //cout<<" basci "<<i<<"        height:"<<up[tmp]<<"    "<<"L;"<<sta.top()+1<<"   R:"<<j-1<<endl;
                }
            }
            sta.push(j);
        }
    }
    cout<<ans<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40642465/article/details/99175741