Largest Rectangle in a Histogram
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 5445 Accepted Submission(s): 1558
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.
对于每一块木板,Area=height[i]*(j-k+1) 设其中任一块x, j<=x<=k, height[x]>=height[i]; 找j,k成为关键。
#include<stdio.h>
#define N 100005
#define MX(a,b) (a>b?a:b)
int l[N],r[N];
__int64 h[N];
__int64 max;
int n;
int main()
{
while(scanf("%d",&n),n)
{
for(int i=1;i<=n;i++)
{
scanf("%I64d",&h[i]);
l[i]=r[i]=i;
}
h[0]=h[n+1]=-1;//高度可能为0,防止死循环;
//利用动态规划,如果它左边高度大于等于它本身,那么它左边的左边界一定满足这个性质,再从这个边界的左边迭代下去;
for(int i=1;i<=n;i++)
{
while(h[l[i]-1]>=h[i])
l[i]=l[l[i]-1];
}
for(int i=n;i>=1;i--)
{
while(h[r[i]+1]>=h[i])
r[i]=r[r[i]+1];
}
max=0;
for(int i=1;i<=n;i++)
max=MX(max, (r[i]-l[i]+1)*h[i] );
printf("%I64d\n",max);
}
return 0;
}