B - Largest Rectangle in a Histogram 题解(单调栈)
程序员文章站
2022-04-01 09:38:30
...
题目链接
题目思路
单调栈求出每个矩形可以向左向右延伸的最大长度。
代码
#include<cstdio>
#include<stack>
#include<cstring>
#include<cmath>
#include<iostream>
#include<algorithm>
#define fi first
#define se second
#define debug printf("I am here\n");
using namespace std;
typedef long long ll;
const int maxn=3e6+5,inf=0x3f3f3f3f;
const ll INF=0x3f3f3f3f3f3f3f3f;
int n,a[maxn];
int sta[maxn],l[maxn],r[maxn];
int main(){
while(scanf("%d",&n)!=-1&&n){
ll ans=0;
for(int i=1;i<=n;i++){
scanf("%d",&a[i]);
}
int top=0;
for(int i=1;i<=n;i++){//枚举右端点
while(top&&a[sta[top]]>=a[i]){
top--;
}
l[i]=top==0?1:sta[top]+1;
sta[++top]=i;
}
top=0;
for(int i=n;i>=1;i--){
while(top&&a[sta[top]]>=a[i]){
top--;
}
r[i]=top==0?n:sta[top]-1;
sta[++top]=i;
}
for(int i=1;i<=n;i++){
ans=max(ans,1ll*(r[i]-l[i]+1)*a[i]);
}
printf("%lld\n",ans);
}
return 0;
}
推荐阅读
-
【题解】hdu1506 Largest Rectangle in a Histogram
-
HDU 1506 Largest Rectangle in a Histogram(单调栈)
-
【题解】hdu1506 Largest Rectangle in a Histogram
-
Largest Rectangle in a Histogram【POJ 2559】【单调栈】
-
Largest Rectangle in a Histogram POJ - 2559(栈的运用)
-
leetcode 84 Largest Rectangle in Histogram (单调栈)
-
B - Largest Rectangle in a Histogram 题解(单调栈)
-
HDU 1506 Largest Rectangle in a Histogram(单调栈)