Largest Rectangle in a Histogram

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.
7 2 1 4 5 1 3 3 4 1000 1000 1000 1000 0
8 4000
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1506
题目大意:n块宽为1,长不等的矩形木板,如图拼凑在一起,求木板覆盖范围内最大矩形的面积。
解题思路:每块木板向左向右延伸,l[i],r[i]记录木板a[i]能延伸范围的左右边界,s=(r[i]-l[i]+1)*a[i],即为木板 a[i]延伸后覆盖的最大矩形面积。注意从前往后更新l[i],从后往前更新r[i],能有效提高效率。
代码如下:
#include <stdio.h>
long long a[100004],l[100004],r[100004];//l[maxn],r[maxn]表示左右边界坐标
int main()
{
int n,i,d;
while(scanf("%d",&n)!=EOF&&n)
{
long long s=0;
a[0]=a[n+1]=-1;
for(i=1;i<=n;i++)
{
scanf("%I64d",&a[i]);
l[i]=r[i]=i; //初始化左右边界的坐标
}
for(i=1;i<=n;i++)
{
while(a[i]<=a[l[i]-1]) //如果还能延伸到边界左边的木板,呃更新边界值。如果后一块木板小于前一块
l[i]=l[l[i]-1];//那后一块必能延伸到前一块木板的边界,有效地减少了循环次数
}
for(i=n;i>=1;i--)
{
while(a[i]<=a[r[i]+1])
r[i]=r[r[i]+1];
}
for(i=1;i<=n;i--)
{
d=(r[i]-l[i])+1;
if(d*a[i]>s)
s=d*a[i];
}
printf("%I64d\n", s);
}
return 0;
}
1万+




被折叠的 条评论
为什么被折叠?



