题目大意:
找到在N*M 的矩阵中第二大全1矩阵的面积是多少
分析:
用一个二维数组dp【i】【j】表示第i行第j列向上最多有多少个连续的1;
然后去暴力枚举每一行
用单调栈去维护当前行的高度,该高度是呈现单调递增的,若栈中维护的的矩阵的高度大于当前dp[i][j],那么就出栈。
每次更新完栈的时候就去更新答案。
其实可以手动模拟栈
#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[1010][1010];
struct node{
int h,w;
};
stack<node>s,tem;
int max1,max2;
void update(int x){
if(x>max1)
max2=max1,max1=x;
else
max2=max(max2,x);
}
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){
rep(j,1,m) {
scanf("%1d",&dp[i][j]);
if(dp[i][j]!=0)
dp[i][j]+=dp[i-1][j];
}
}
for(int i=1;i<=n;i++){
while(!s.empty()) s.pop();//遍历每一行都要从新建立单调栈,保证栈里面的矩阵的高是递增存放的
for(int j=1;j<=m;j++){
if(dp[i][j]==0){//断开了,说明前面的存在的矩阵已没有意义,需要从新开始
while(!s.empty()) s.pop();
continue;
}
int res=j;
while(!s.empty() && s.top().h>dp[i][j]){//以前存储的矩阵太高了
res=s.top().w;//该矩阵的右边界
s.pop();
}
if(s.empty() || s.top().h!=dp[i][j]) s.push((node){dp[i][j],res});//加入新的右边界与高
while(!s.empty()){
node u=s.top();
s.pop();
update(u.h*(j-u.w+1));
tem.push(u);
}
while(!tem.empty()){
node u=tem.top();
tem.pop();
s.push(u);
}
}
}
printf("%d\n",max2);
return 0;
}