Largest Rectangle in a Histogram
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 11541 Accepted Submission(s): 3174
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.
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
Source
题意: 给你一个条形图,数值,如上图,要你求出其最大矩形.....
就是给定了你的h(高),要你求宽度....宽度这个是等于j-i+1这样一个长度:
对于任意一个位置,我们只需要找到他可以组合的最左边,和最右边就可以求出宽度...
于是,(这个思想是参考discuss里别人的....╮(╯▽╰)╭,然后自己理解的)我们不妨做两次求值:
首先从1~~N ,遍历,对于pos这个位置,求出左边比他高的数的下标.....
然后,从N~~!遍历,对于pos这个位置,求出右边比他高的数的下标.....
比如:
7 2 1 4 5 1 3 3 这组数:
求解步骤:
pos 1 2 3 4 5 6 7
val 2 1 4 5 1 3 3
ll[] 1 1 3 4 1 6 6 1->n
rr[] 1 7 4 4 7 7 7 n->1
res=(rr[pos]-ll[pos])*hh[pos];
代码:
1 #include<cstdio> 2 #include<cstring> 3 #define maxn 100005 4 __int64 ll[maxn],rr[maxn],hh[maxn]; 5 int main() 6 { 7 int n,i,t; 8 while(scanf("%d",&n)&&n) 9 { 10 for(i=1;i<=n;i++) 11 scanf("%I64d",&hh[i]); 12 ll[1]=1,rr[n]=n; 13 for(i=2;i<=n;i++) 14 { 15 t=i; 16 while(t>1&&hh[i]<=hh[t-1]) 17 t=ll[t-1]; 18 ll[i]=t; 19 } 20 for(i=n-1;i>0;i--) 21 { 22 t=i; 23 while(t<n&&hh[i]<=hh[t+1]) 24 t=rr[t+1]; 25 rr[i]=t; 26 } 27 __int64 res=0; 28 for(i=1;i<=n;i++) 29 { 30 if(res<(rr[i]-ll[i]+1)*hh[i]) 31 res=(rr[i]-ll[i]+1)*hh[i]; 32 } 33 printf("%I64d ",res); 34 } 35 return 0; 36 }