http://acm.hdu.edu.cn/showproblem.php?pid=1506
A histogram is a polygon composed of a sequence of rectangles aligned at a common base line. The rectangles have equal widths but may have different heights. For example, the figure on the left shows the histogram that consists of rectangles with the heights 2, 1, 4, 5, 1, 3, 3, measured in units where 1 is the width of the rectangles:
Usually, histograms are used to represent discrete distributions, e.g., the frequencies of characters in texts. Note that the order of the rectangles, i.e., their heights, is important. Calculate the area of the largest rectangle in a histogram that is aligned at the common base line, too. The figure on the right shows the largest aligned rectangle for the depicted histogram.
题意:求最大的矩形面积。
思路:预处理出以每一个点的高为矩形的高,向左、向右最多可以扩展多少。即每个位置的左/右方第一个比它小的位置,解决这个问题的一般方法就是单调栈,O(n)。和这道题一样https://blog.csdn.net/Wen_Yongqi/article/details/87364385。
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<stack>
using namespace std;
#define maxn 100000+100
#define ll long long
ll n,a[maxn],l[maxn],r[maxn],ans;
int main()
{
//freopen("input.in","r",stdin);
while(cin>>n&&n)
{
ans=-1;
for(ll i=1;i<=n;i++)scanf("%lld",&a[i]);
a[0]=a[n+1]=-1;
stack<int> s;
for(int i=1;i<=n+1;i++)
{
while(!s.empty()&&a[i]<a[s.top()])
{
r[s.top()]=i;
s.pop();
}
s.push(i);
}
while(!s.empty())s.pop();
for(int i=n;i>=0;i--)
{
while(!s.empty()&&a[i]<a[s.top()])
{
l[s.top()]=i;
s.pop();
}
s.push(i);
}
for(int i=1;i<=n;i++)
{
int L=l[i]+1,R=r[i]-1;
ans=max(ans,a[i]*(R-L+1));
}
cout<<ans<<"\n";
}
return 0;
}