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: 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); 代码如下:
#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=;
const double eps=0.00000001;
typedef __int64 LL;
LL H[],le[],ri[],que[]; //高度,左边界,右边界,单调栈
int main()
{
int N;
while(cin>>N)
{
if(!N) break;
for(int i=;i<=N;i++) scanf("%I64d",&H[i]);
int rear=;
for(int st=;st<=N;st++) //从左往右扫,找le[]
{
while(rear>&&H[que[rear]]>=H[st]) --rear; //更新
if(rear==) le[st]=; //如果栈空的话,边界设为0
else le[st]=que[rear];
que[++rear]=st; //入栈
}
rear=;
for(int st=N;st>=;st--) //从右往左扫
{
while(rear>&&H[que[rear]]>=H[st]) --rear;
if(rear==) ri[st]=N+;
else ri[st]=que[rear];
que[++rear]=st;
}
LL ans=;
for(int i=;i<=N;i++) if(ans<H[i]*(ri[i]-le[i]-)) ans=H[i]*(ri[i]-le[i]-); // 答案
cout<<ans<<endl;
}
return ;
}