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
给出一个直方图的各列的高,宽度相同,求直方图中面积最大的矩形
题解:已每个点为组成矩形的最低点,向左右延伸
代码是参考别人的,然后加了一点自己的理解
1 #include<stdio.h> 2 int r[100010], l[100010]; 3 long long s[100010]; 4 int main() { 5 int n, i, j; 6 long long ans, temp; 7 while (scanf("%d", &n), n) { 8 for (i = 1; i <= n; i++) { 9 scanf("%lld", &s[i]); 10 l[i] = r[i] = i; 11 } 12 s[n + 1] =s[0] = -1; 13 for (i = 1; i <= n; i++) { 14 while (s[l[i] - 1] >= s[i]) 15 l[i] = l[l[i] - 1];//因为有了这层数组嵌套,才能体现动态规划 16 } //的优点,表示l[i]是在前一个的基础上得到的,那下次就 17 for (i = n; i >= 1; i--) { //不用再重复计算前一个了,数据多的时候, 18 while (s[i] <= s[r[i] + 1]) //可以节省很多时间 19 r[i] = r[r[i] + 1]; 20 } 21 ans = 0; 22 for (i = 1; i <= n; i++) { 23 temp = s[i]*(r[i] - l[i] + 1) ; 24 if (temp > ans)ans = temp; 25 } 26 printf("%lld\n", ans); 27 } 28 return 0; 29 }