Problem 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.
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
思路:
这个就是一个乱搞的题目,首先暴力肯定不行。
我们这么去求各个情况的面积,若value[2]=3,那么我们就求第二个方格上最大高度为3的扩展是多少。即其他合法的位置方格都不低于起始位置。
我们可以看到,比如求向左的扩展时,如果某位置的value[pos]>value[i]时,我们直接可以扩展到将l[i]=l[pos],在[l[pos],pos]之间大于value[pos],那么也大于value[i]依次跳转即可。
#include<bits/stdc++.h>
#define input freopen("input.txt","r",stdin)
using namespace std;
long long l[100010],r[100010];
long long value[100010],maxx;
int main()
{
input;
int n,i,j,left,right;
while(cin>>n&&n)
{
memset(l,0,sizeof(l));
memset(r,0,sizeof(r));
for(i=1;i<=n;i++)
{
cin>>value[i];
}
l[1]=1;
for(i=2;i<=n;i++)
{
left=i;
while(1)
{
if(left==1)break;
if(value[left-1]>=value[i])
{
left=l[left-1];
}
else
{
break;
}
}
l[i]=left;
}
r[n]=n;
for(i=n-1;i>=1;i--)
{
right=i;
while(1)
{
if(right==n)break;
if(value[right+1]>=value[i])
{
right=r[right+1];
}
else
{
break;
}
}
r[i]=right;
}
for(maxx=0,i=1;i<=n;i++)
{
if((r[i]-l[i]+1)*value[i]>maxx)
{
maxx=(r[i]-l[i]+1)*value[i];
}
}
cout<<maxx<<endl;
}
return 0;
}