2019牛客暑期多校训练营(第八场) A All-one Matrices 【单调栈】

All-one Matrices
在这里插入图片描述
在这里插入图片描述
题意:
求给出的n*m的矩阵中全一的不可扩展的最大子矩阵
这篇博客里面有对题意的样例解释(在后面)https://blog.csdn.net/weixin_43720526/article/details/99210681

分析:
官方给出的题解是先用一个二维数组dp[i][j[表示第i行第j列这个位置向上有多少连续的1,然后再用一个二维数组sum[i][j]表示第i行的前缀和,用于单调栈的判断。

怎么判断呢:可以先看一下这篇文章https://blog.csdn.net/c___c18/article/details/99329450
这个也是单调栈处理矩阵的,但比这题简单
了解了这个以后,就可以知道,我们用单调栈去保存着当前这个全一的矩阵的左边界是多少,同时也保留了右边界,然后,你就需要判断下边界是不是也是全一,这个时候就用到我们定义的前缀和了

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<string>
#include<cmath>
#include<cstring>
#include<set>
#include<queue>
#include<stack>
#include<map>
#define rep(i,a,b) for(int i=a;i<=b;i++)
typedef long long ll;
using namespace std;
const int N=1e5+10;
const int INF=0x3f3f3f3f;
int dp[3010][3010],sum[3010][3010];
char str[3010];
struct node{
    int h,w;
};
stack<node>s;
int main()
{
    #ifndef ONLINE_JUDGE
    freopen("in.txt","r",stdin);
    #endif // ONLINE_JUDGE
    int n,m;
    scanf("%d%d",&n,&m);
    rep(i,1,n){
            scanf("%s",str+1);
        rep(j,1,m){
            sum[i][j]=sum[i][j-1]+(str[j]-'0');
            if((str[j]-'0'))
            dp[i][j]=dp[i-1][j]+1;
        }
    }
    int ans=0;
    for(int i=1;i<=n;i++){
        while(!s.empty()) s.pop();
        for(int j=1;j<=m+1;j++){//j要到m+1,这样才能处理单行的情况

            int res=j;
            while(!s.empty() && s.top().h>= dp[i][j]){
                res=s.top().w;
                int l=res,r=j-1;
                if(dp[i][j]< s.top().h)//相等的话会判重,没有意义
                if(sum[i+1][r]-sum[i+1][l-1]!=r-l+1)//看能否向下延申
                    ans++;

                s.pop();
            }
            if(dp[i][j]==0) {
        while(!s.empty()) s.pop();
                continue;
            }
            s.push((node){dp[i][j],res});
        }
    }
    printf("%d\n",ans);
    return 0;
}


发布了229 篇原创文章 · 获赞 17 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/c___c18/article/details/99339996