题解报告: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: 
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代码:
 1 #include<cstdio>
 2 #include<iostream>
 3 #include<algorithm>
 4 #include<string.h>
 5 #include<stack>
 6 using namespace std;
 7 typedef long long LL;
 8 const int maxn=1e5+5;
 9 int n,L[maxn],R[maxn];LL res,h[maxn];
10 stack<int> st;
11 int main(){
12     while(~scanf("%d",&n)&&n){
13         while(!st.empty())st.pop();memset(L,0,sizeof(L));memset(R,0,sizeof(R));
14         for(int i=0;i<n;++i)scanf("%lld",&h[i]);
15         for(int i=0;i<n;++i){
16             while(!st.empty()&&h[st.top()]>=h[i])st.pop();//找到i左边第一个比hi小的j右边一个点j+1,左闭
17             L[i]=st.empty()?0:st.top()+1;//如果栈空,说明hi不大于左边所有高度,那么区间左端点可延伸至0,这里为了方便计算区间长度
18             st.push(i);//再压入当前左端点值i
19         }
20         while(!st.empty())st.pop();res=0;
21         for(int i=n-1;i>=0;--i){
22             while(!st.empty()&&h[st.top()]>=h[i])st.pop();//找到i右边第一个比hi小的j,右开
23             R[i]=st.empty()?n:st.top();//如果栈空,说明hi不大于右边所有高度,那么区间右端点可延伸至n,同样为了方便计算区间长度
24             st.push(i);//再压入当前右端点值i
25         }
26         for(int i=0;i<n;++i)//找最大面积
27             res=max(res,h[i]*(R[i]-L[i]));
28         cout<<res<<endl;
29     }
30     return 0;
31 }
原文地址:https://www.cnblogs.com/acgoto/p/9536271.html