HDU-1506 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:
HDU-1506 Largest Rectangle in a 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

Hint

Huge input, scanf is recommended.

Source

 
思路:单调栈题。用一个deque代替栈来模拟。记录每个矩形长度为1,用一个totlen保存当前所有矩形的长度,枚举每个矩形的高度h,维护最大面积maxx。
有一个关键的对maxx的更新在于碰到不单调情况时,一直往左边pop找到一个小于当前读入的矩形高度的合法值,这个pop掉的矩形是一个单独凸起的高度的,需要单独记录一次面积。
最后,若队列中仍有元素,更新一遍maxx。
 
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <deque> using namespace std;
typedef __int64 LL;
const int maxn=1e5+7; LL maxx; struct node{
LL len;
LL h;
}a[maxn]; int main()
{
LL n;
while(~scanf("%I64d",&n)&&n){
for(LL i=0;i<n;i++)
{
scanf("%I64d",&a[i].h);
a[i].len=1;
}
deque <node> q;
q.push_back(a[0]);
maxx=0;
for(LL i=1;i<n;i++)
{
if(a[i].h>=a[i-1].h)
{
q.push_back(a[i]);
}
else
{
LL totlen=0;
LL ae=0;
while(!q.empty()&&a[i].h<q.back().h)
{
totlen+=q.back().len;
ae=totlen*q.back().h;
maxx=max(maxx,ae);
q.pop_back();
}
totlen+=a[i].len;
a[i].len=totlen;
q.push_back(a[i]);
}
} LL totlen=0,ae=0; while(!q.empty())
{
totlen+=q.back().len;
ae=totlen*q.back().h;
maxx=max(maxx,ae);
q.pop_back();
}
printf("%I64d\n",maxx);
}
return 0;
}
上一篇:北京Uber优步司机奖励政策(2月19日)


下一篇:题解报告:poj 2559 Largest Rectangle in a Histogram(单调栈)