Largest Rectangle in a Histogram
HDU - 1506题意:n个宽为1, 高不定的矩形, 以宽为底, 按给出顺序排列, 找出其中所能构成的最大的矩形的面积;
每个小矩形所在的最大矩阵是从他左边第一个小于他的矩形到右边第一个小于他的矩形的区间;
用单调栈, 找到l[i], r[i];(分别表示左边第一个小于的数,右边第一个小于的数);
ans=max( h[i]*(r[i]-l[i]-1) );
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <stack>
using namespace std;
const int maxn=1e5+100;
long long h[maxn], l[maxn], r[maxn];
stack<int> sta;
int main(){
int n;
while(~scanf("%d", &n), n){
for(int i=1; i<=n; i++){
scanf("%lld", &h[i]);
}
while(!sta.empty()) sta.pop();
h[0]=h[n+1]=-1;
sta.push(0);
for(int i=1; i<=n; i++){
while(!sta.empty()&&h[sta.top()]>=h[i]) sta.pop();
l[i]=sta.top();
sta.push(i);
}
while(!sta.empty()) sta.pop();
sta.push(n+1);
for(int i=n; i>0; i--){
while(!sta.empty()&&h[sta.top()]>=h[i]) sta.pop();
r[i]=sta.top();
sta.push(i);
}
long long ans=0;
for(int i=1; i<=n; i++){
ans=max(ans, h[i]*(r[i]-l[i]-1));
}
printf("%lld\n", ans);
}
return 0;
}