Largest Rectangle in a Histogram
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 6825 | Accepted: 2074 |
Description
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.
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.
Input
The input contains several test cases. Each test case describes a histogram and starts with an integer
n, denoting the number of rectangles it is composed of. You may assume that
1<=n<=100000. Then follow
n integers
h1,...,hn, where
0<=hi<=1000000000. These numbers denote the heights of the rectangles of the histogram in left-to-right order. The width of each rectangle is
1. A zero follows the input for the last test case.
Output
For each test case output on a single line the area of the largest rectangle in the specified histogram. Remember that this rectangle must be aligned at the common base line.
Sample Input
7 2 1 4 5 1 3 3 4 1000 1000 1000 1000 0
Sample Output
8 4000 这个题目是我写的第二个关于秋最大子矩阵的题目,想了很久才做出来,是自己比较满意的一个程序。要注意是__int64型的,不然会
WA。下面是我的程序,很简单,就是用数组保存该列的左边和右边比该列大的个数,要注意是以该列为头的连续的个数。呵呵,还是大家
看我的程序吧!!
//172ms 2512K
#include<stdio.h>
#include<string.h>
//#include<iostream.h>
__int64 value[100002],n,left[100002],right[100002];
int main()
{
while(scanf("%I64d",&n)&&n)
{
__int64 i,j,ans=0;
for(i=1;i<=n;i++)
scanf("%I64d",&value[i]);
//memset(left,1,sizeof(left));
//memset(right,1,sizeof(right));
//value[0]=value[n+1]=0;
for(i=1;i<=n;i++) left[i]=1;
for(i=1;i<=n;i++) right[i]=1;
for(i=2;i<=n;i++)
{
for(j=i-1;j>0;)
{
if(value[i]<=value[j])
{
left[i]+=left[j];
j-=left[j];
}
else break;
}
}
for(i=n-1;i>=1;i--)
{
for(j=i+1;j<=n;)
{
if(value[i]<=value[j])
{
right[i]+=right[j];
j+=right[j];
}
else
break;
}
}
//for(i=1;i<=n;i++) cout<<left[i]<<" ";
//cout<<endl;
//for(i=1;i<=n;i++) cout<<right[i]<<" ";
//cout<<endl;
for(i=1;i<=n;i++)
{
j=(right[i]+left[i]-1)*value[i];
if(j>ans) ans=j;
}
printf("%I64d/n",ans);
}
return 0;
}