链接:https://ac.nowcoder.com/acm/contest/882/H
解法:单调栈
做法是,计算以每一行为底的最大矩形,可以得到每个矩形的长宽,这样就可以计算出次大矩形。枚举每一列i,对于每一列i的每一列,计算出i行j列处的值向上有多少个连续的1,即h[j],将h[j]加入到一个单调递增栈中,见代码
最好手动模拟一下,比如:
3 4
0010
0110
0111
计算到最后一行,h[]={0,2,3,1,-1}
1.栈空,下标0入栈
2.2>=h[栈顶],下标1入栈
3.3>=h[栈顶],下标2入栈
4.1<=h[栈顶],top=栈顶,x=当前下标(3)-top(2)=1,y=h[top]=3,用xy、x(y-1)和(x-1)*y更新最大值和次大值,弹栈;继续4,在栈顶等于0,top=1后跳出循环,将h[top]置为h[当前下标],top进栈
5.-1<=h[栈顶],x=4-1=3,y=h[top]=1,更新答案,跳出循环
输出答案
这个题的简化版是这个 https://blog.csdn.net/qq_41646772/article/details/96706137
#include <bits/stdc++.h>
using namespace std;
const int maxN=1e3+5;
int N,M,h[maxN],a[maxN],ans,ma;
string str;
stack<int> sta;
void solve(int s)//更新最大和次大值
{
if(ma<=s)
{
ans=ma;
ma=s;
}
else ans=max(ans,s);
}
int main()
{
scanf("%d%d",&N,&M);
for(int i=0; i<N; i++)
{
cin>>str;
for(int j=0; j<M; j++)
{
if(str[j]=='0')a[j]=0;
else a[j]+=1;
h[j]=a[j];
}
h[M]=-1;//末尾追加-1,方便处理边界情况
while(!sta.empty())sta.pop();//每枚举新的一行,清空栈
for(int j=0; j<=M; j++)
{
if(sta.empty()||h[j]>=h[sta.top()])sta.push(j);//值单调递增,下标入栈
else
{
int top;
while(!sta.empty()&&h[j]<h[sta.top()])
{
top=sta.top();
int x=j-top,y=h[top];
sta.pop();
solve(x*y);
solve((x-1)*y);
solve(x*(y-1));
}
sta.push(top);
h[top]=h[j];
}
}
}
printf("%d",ans);
return 0;
}