A - 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.
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
Hint
Huge input, scanf is recommended.

解:
首先想到的肯定是暴力枚举,寻找向左向右能延伸的最大长度,求出最大值。基本上是O(n^2)的时间复杂度。(不过这题数据水,能过)。
此题为单调栈的入门题/(ㄒoㄒ)/~~。维护一个单调递增栈,每读取一个长方形高度h,就和栈顶数字作比较,如果h比栈顶数字小,那么为了维护单调性,必须将栈内所有大于h的数字pop出去,因此左边的元素必然小于右边的元素,只需要记录向右延伸的最大距离,放入数组记录,每pop出去一个数,就要计算一次最大面积,完成后再push入新数据。
根据该算法判断条件,可以在开头和结尾各补一个高为0或者负数的“长方形”,避免边界问题。

#include <stack>
#include <algorithm>
#include <math.h>
using namespace std;
const int N = 101000;
int lst[N];
stack<int> st;//构建栈
int dis[N];//该长方形到右边的最大距离(包括自己)
int main()
{
    ios::sync_with_stdio(false);//加快读入速度
    int n;
    while (cin >> n)
    {
        if (n == 0)
            break;
        for (int i = 1; i < n + 1; i++)
        {
            cin >> lst[i];
        }
        lst[n + 1] = 0;//后补0
        long long ans = 0;
        st.push(0);//前补0
        for (int i = 1; i <= n + 1; i++)
        {
            int tmp = 0;//临时存储最大距离
            while (st.top() > lst[i])
            {
                tmp += dis[st.size()-1];
                ans = max(ans, (long long) st.top() * tmp);
                st.pop();
            }
            st.push(lst[i]);//数据入栈
            dis[st.size()-1] = tmp + 1;//加上自己的“1”
        }
        cout << ans << endl;
    }
    return 0;
}