经典单调栈最大子矩形——牛客多校第二场H

题目是求次大子矩形,那么在求最大子矩形的时候维护M1,M2即可

转移M2时比较的过程要注意一下

#include<bits/stdc++.h>
using namespace std;
#define maxn 1005
char mp[maxn][maxn];
int n,m,f[maxn][maxn],M1,M2;

int stk[maxn],top,w[maxn];
void calc(int i){
    top=0;
    f[i][m+1]=0;
    memset(w,0,sizeof w);
    for(int j=1;j<=m+1;j++)
        if(f[i][j]>stk[top]){
            stk[++top]=f[i][j];
            w[top]=1;
        }     
        else {
            int width=0;
            while(f[i][j]<stk[top]){
                width+=w[top];
                
                if(stk[top]*(width)>=M1){
                    M2=max(M1,stk[top]*(width-1));//这里的用M1和高度*(宽度-1)相比较,大的更优
                    M1=stk[top]*(width);
                }
                else
                    M2=max(M2,stk[top]*width);
                    
                top--;
            }
            stk[++top]=f[i][j],w[top]=width+1;
        }
} 

int main(){
    cin>>n>>m;
    for(int i=1;i<=n;i++)scanf("%s",mp[i]+1);
    for(int i=1;i<=n;i++){
        for(int j=1;j<=m;j++)
            if(mp[i][j]=='1')
                f[i][j]=f[i-1][j]+1;
            else f[i][j]=0;
    }
    for(int i=1;i<=n;i++)
        calc(i);
    cout<<M2<<endl;
}

猜你喜欢

转载自www.cnblogs.com/zsben991126/p/11286257.html