单调栈
Problem Description
hdu-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.
Analysis of ideas
求这个图形可以组成的最大的矩形的面积
如果我们枚举每一个点,再枚举左边和右边可以扩展的长度,那么时间复杂度是 \(O(n^2)\) 的
如果把左边和右边可以扩展的长度预处理出来,就可以在 \(O(n)\) 的时间内解决了
Accepted code
#include <bits/stdc++.h>
using namespace std;
#define ll long long
const int maxn = 100100;
ll a[maxn];
int l[maxn],r[maxn];
stack <int> s;
int main()
{
int n;
while(cin>>n && n)
{
for(int i = 1; i <= n; i++)
{
scanf("%lld",&a[i]);
}
while(!s.empty())
s.pop();
for(int i = 1; i <= n; i++)
{
while(!s.empty() && a[s.top()] >= a[i])
s.pop();
if(s.empty())
l[i] = 1;
else
l[i] = s.top()+1;
s.push(i);
}
while(!s.empty())
s.pop();
for(int i = n; i >= 1; i--)
{
while(!s.empty() && a[i] <= a[s.top()])
s.pop();
if(s.empty())
r[i] = n+1;
else
r[i] = s.top();
s.push(i);
}
ll ans = 0;
for(int i = 1; i <= n; i++)
{
ans = max(ans,a[i]*(r[i]-l[i]));
}
printf("%lld\n",ans);
}
return 0;
}