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: ![](http://7xjob4.com1.z0.glb.clouddn.com/45660aba95464e61adfbbcc7cea2c44c)
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
题意:从左到右有N个高度不同但底边边长为1的矩形,问从中能够裁出的最大面积的矩形的面积是多少。而且矩行的边必须与纵轴、横轴平行。
解析:设置两个数组le[],ri[],分别表示以某个小矩形为起点,向左、向右能延伸的最远位置(比该小矩形的高度小的)用单调栈维护,我写的le[],ri[]是第一个不符合条件的位置,
所以面积=h[i]*(ri[i]-le[i]-1);
代码如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include<cstdio> #include<cstring> #include<string> #include<algorithm> #include<set> #include<map> #include<queue> #include<vector> #include<iterator> #include<utility> #include<sstream> #include<iostream> #include<cmath> #include<stack> using namespace std; const int INF=1000000007; const double eps=0.00000001; typedef __int64 LL; LL H[100005],le[100005],ri[100005],que[100005]; //高度,左边界,右边界,单调栈 int main() { int N; while(cin>>N) { if(!N) break; for(int i=1;i<=N;i++) scanf("%I64d",&H[i]); int rear=0; for(int st=1;st<=N;st++) //从左往右扫,找le[] { while(rear>0&&H[que[rear]]>=H[st]) --rear; //更新 if(rear==0) le[st]=0; //如果栈空的话,边界设为0 else le[st]=que[rear]; que[++rear]=st; //入栈 } rear=0; for(int st=N;st>=1;st--) //从右往左扫 { while(rear>0&&H[que[rear]]>=H[st]) --rear; if(rear==0) ri[st]=N+1; else ri[st]=que[rear]; que[++rear]=st; } LL ans=0; for(int i=1;i<=N;i++) if(ans<H[i]*(ri[i]-le[i]-1)) ans=H[i]*(ri[i]-le[i]-1); // 答案 cout<<ans<<endl; } return 0; }