HDU 1506 Largest Rectangle in a Histogram(最大矩形面积)
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
题意:找出最大的矩形面积。
思路:对每个a[i],找出左右两边连续的大于a[i]的数的长度。l[i]记录a[i]左边大于a[i]的数的长度,r[i]记录a[i]右边大于a[i]的数的长度.最后(r[i]-l[i]+1)*a[i]找出最大的矩形
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #define NN 100002 5 using namespace std; 6 long long a[NN], l[NN], r[NN]; 7 int main() 8 { 9 int i, j, n, t; 10 long long MaxV; 11 while(~scanf("%d", &n),n) 12 { 13 for(i = 1; i <= n; i++) 14 scanf("%lld", &a[i]); 15 l[1] = 1; 16 for(i = 2; i <= n; i++){ 17 t = i; 18 while(t > 1 && a[i] <= a[t-1])t = l[t-1]; 19 l[i] = t; 20 } 21 r[n] = n; 22 for(i = n-1; i > 0; i--){ 23 t = i; 24 while(t < n && a[i] <= a[t+1])t = r[t+1]; 25 r[i] = t; 26 } 27 MaxV = -100; 28 for(i = 1; i <= n; i++){ 29 if((r[i] - l[i] + 1) * a[i] > MaxV)MaxV = (r[i] - l[i] + 1) * a[i]; 30 } 31 cout<<MaxV<<endl; 32 } 33 return 0; 34 }