Largest Rectangle in a Histogram@HDU 1506

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

题目分析:对于这个题而言,当且仅当一个矩形的左右边界的高度都小于这个矩形的高(即这个矩形包含的最小的高度)时,这个矩形的面积是最大的。可以用反证法证明:假设这个矩形的左边界的高度是大于或等于这个矩形的高的,那么这个矩形一定不是面积最大的矩形,因为这个矩形的面积+左边界的面积一定大于这个矩形的面积。

所以对于每个点i(注意i代表的是数组下标),我们要分别找到从左遍历第一个比i小的点的坐标和从右遍历第一个比i小的点的坐标,这样就确定了以i为高的最大面积矩形的左右边界,然后枚举出最大值。 

#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
#include <cstring>
#include <cstdio>
#include <stack>
#define MAXN 100003
using namespace std;

int h[MAXN];
int l[MAXN],r[MAXN];

int main(){
    int n;
    stack<int> s;
    while(~scanf("%d",&n) && n){
        for(int i=0;i<n;++i) scanf("%d",&h[i]);
        while(!s.empty()) s.pop();
        for(int i=0;i<n;++i){
            while(!s.empty() && h[i] <= h[s.top()]) s.pop();
            if(!s.empty()) l[i] = s.top();
            else l[i] = -1;
            s.push(i);
        }
        while(!s.empty()) s.pop();
        for(int i=n-1;i>=0;--i){
            while(!s.empty() && h[i] <= h[s.top()]) s.pop();
            if(!s.empty()) r[i] = s.top();
            else r[i] = n;
            s.push(i);
        }
        long long ans = 0;
        for(int i=0;i<n;++i){
            ans = max(ans,(long long)h[i]*(r[i]-l[i]-1));
        }
        cout << ans << endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_39021458/article/details/81241195