Largest Rectangle in a Histogram(单调栈)

题目链接: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:
Largest Rectangle in a Histogram(单调栈)_第1张图片

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

思路:单调栈,写的时候还不太会,想着想着就弄懂了。
首先是,我想到了单调递增子序列,才想到了这种思路(单调栈),因为遇到递减的时候就可以更新最大的矩阵了,并且更新刚放进去的点的长度,因为你放进去的数是小于栈头的元素的。

代码:

#include 
#include 
#include 
#include
#include 
#include
#include 
#include 
#include 
using namespace std;
typedef long long ll;
const int maxn=1e5+9;
struct node
{
    ll id;
    ll h;
}a[maxn];
stacks;

int main()
{
    ll n;
    while(~scanf("%lld",&n),n)
    {
        while(!s.empty())s.pop();
        node p;
        ll ans=-1;//最终答案
        for(ll i=1; i<=n; i++)
        {
            scanf("%lld",&a[i].h);//高度
            a[i].id=i;//原始的位置
        }
        a[n+1].h=0,a[n+1].id=(ll)n+1;//加一个最小的,以便在最后将栈清空
        for(ll i=1; i<=n+1; i++)
        {
            ll x=a[i].h;
            if(s.size()==0||s.top().h//严格的单调递增
                s.push(a[i]);
            else
            {
                while(!s.empty()&&s.top().h>=x)//小于等于它的,全去掉
                {
                    node p1=s.top();
                    s.pop();
                    a[i].id=p1.id;//更新a[i]的位置,因为他们都比a[i]高
                    ll len=(ll)i-p1.id;
                    if(len*p1.h>ans)//更新最大值
                        ans=len*p1.h;
                }
                s.push(a[i]);
            }
        }
        printf("%lld\n",ans);
    }
    return 0;
}

你可能感兴趣的:(栈,ACM,题目,算法)