【poj2559】Largest Rectangle in a Histogram

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.

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, where0<=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.

Source

 
/*
    维护一个栈中元素(高度)单调递增的栈 
    扫描每个矩形,若比栈顶元素高就直接进栈
    否则弹出栈顶,直至递增,弹栈过程中累计弹出元素的宽度和,每弹出一个就用弹出高度*累计宽度更新答案。
    最后给当前矩形的宽度加上累计宽度,入栈。
    扫描结束后,依次弹出栈顶元素,按相同方法更新答案,直至栈为空 
*/
#include<cstdio>
#include<iostream>
using namespace std;
long long h[100010];
struct node
{
    long long hei,wid;
}stack[100010];
int n,head=0;
long long widsum=0,ans=0;
int main()
{
    while (scanf("%d",&n) && n)
    {
        ans=0;    head=0;    stack[head].hei=-1;
        for (int i=1;i<=n;i++)    
        scanf("%lld",&h[i]);
        h[++n]=0;
        for (int i=1;i<=n;i++)
        {
            if (h[i]>=stack[head].hei)//大于栈顶元素,直接入栈 
            {
                stack[++head].hei=h[i];
                stack[head].wid=1;
            }
            else
            {
                widsum=0;
                while (stack[head].hei>h[i])//不断弹出栈顶元素 直至递增 
                {
                    widsum+=stack[head--].wid;
                    ans=max(ans,stack[head+1].hei*widsum);//用弹出高度*累计宽度更新答案 
                }
                stack[++head].hei=h[i];
                stack[head].wid=widsum+1;//给当前矩形的宽度加上累计宽度入栈 
            }
        }
        printf("%lld\n",ans);
    }
}

 

posted @ 2016-02-14 09:51  mengyue  阅读(197)  评论(0编辑  收藏  举报