CQUOJ 1482 - 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
1 /* 2 2016年4月23日17:31:55 3 4 DP 找出 a[i] 的左边和右边与自己连着的比自己大的数的长度 , 5 然后用这个长度乘以 a[i], 乘积最大的那个就是答案 6 7 分析:对于每个单位矩阵,我们先求出连续比它高的最左边的下标假设为L, 8 然后求出比它高的最右边的下标假设为R, 9 然后矩阵的面积就是(R-L+1)*h;我们从左到右扫一遍, 10 求出每个点的L保存在L[]数组里, 11 然后从右到左扫一遍,求出每个点的R保存在R[]数组里, 12 最后可以求出最大的矩阵了。 13 */ 14 15 # include <iostream> 16 # include <cstdio> 17 # include <cstring> 18 # include <algorithm> 19 # include <queue> 20 # include <vector> 21 # include <cmath> 22 # define INF 0x3f3f3f3f 23 using namespace std; 24 const int N = 1e5 + 5; 25 26 int L[N], R[N]; 27 long long a[N]; 28 29 int main(void) 30 { 31 int n, i, j, t; 32 long long ans, len; 33 while (~scanf("%d", &n) && n) 34 { 35 for (i = 1; i <= n; i++) 36 scanf("%I64d", &a[i]); 37 L[1] = 1; 38 for (i = 2; i <= n; i++){ 39 t = i; 40 while (t>1 && a[i]<=a[t-1]) 41 t = L[t-1]; 42 L[i] = t; 43 } 44 R[n] = n; 45 for (i = n-1; i >= 1; i--){ 46 t = i; 47 while (t<n && a[i]<=a[t+1]) 48 t = R[t+1]; 49 R[i] = t; 50 } 51 ans = -1; 52 for (i = 1; i <= n; i++){ 53 len = R[i] - L[i] + 1; 54 ans = max(ans, len*a[i]); 55 } 56 printf("%I64d\n", ans); 57 } 58 59 return 0; 60 }

浙公网安备 33010602011771号