题解报告:poj 2559 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: 
题解报告:poj 2559 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
解题思路:题意很清楚,就是找最大覆盖矩形的面积。这里要用到单调递增栈,相关讲解-->单调栈总结。其作用就是找到当前hi向左向右能延伸出最大长度的区间,即[L,R),最后最大的矩形面积就是max{(R[i]-L[i])*h[i]|0<=i<n}。时间复杂度是O(n)。
AC代码:
 #include<cstdio>
#include<iostream>
#include<algorithm>
#include<string.h>
#include<stack>
using namespace std;
typedef long long LL;
const int maxn=1e5+;
int n,L[maxn],R[maxn];LL res,h[maxn];
stack<int> st;
int main(){
while(~scanf("%d",&n)&&n){
while(!st.empty())st.pop();memset(L,,sizeof(L));memset(R,,sizeof(R));
for(int i=;i<n;++i)scanf("%lld",&h[i]);
for(int i=;i<n;++i){
while(!st.empty()&&h[st.top()]>=h[i])st.pop();//找到i左边第一个比hi小的j右边一个点j+1,左闭
L[i]=st.empty()?:st.top()+;//如果栈空,说明hi不大于左边所有高度,那么区间左端点可延伸至0,这里为了方便计算区间长度
st.push(i);//再压入当前左端点值i
}
while(!st.empty())st.pop();res=;
for(int i=n-;i>=;--i){
while(!st.empty()&&h[st.top()]>=h[i])st.pop();//找到i右边第一个比hi小的j,右开
R[i]=st.empty()?n:st.top();//如果栈空,说明hi不大于右边所有高度,那么区间右端点可延伸至n,同样为了方便计算区间长度
st.push(i);//再压入当前右端点值i
}
for(int i=;i<n;++i)//找最大面积
res=max(res,h[i]*(R[i]-L[i]));
cout<<res<<endl;
}
return ;
}
上一篇:HDU-1506 Largest Rectangle in a Histogram【单调栈】


下一篇:分享:PHP获取MAC地址的实现代码