Largest Rectangle in a Histogram
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 26631 | Accepted: 8613 |
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
Hint
Huge input, scanf is recommended.
柱状图是由一些宽度相等的矩形下端对齐后横向排列得到的图形。现在有n个宽度为1,高度分别为h1,h2,……,hn的矩形从左到右依次排列组成的柱状图。问里面包含的矩形的最大面积是多少。
设L[i]为第i个矩形向左遍历得到的第一个小于h[i]的下标,R[i]为第i个矩形向右遍历得到的第一个小于h[i]的下标。
则答案为max(h[i]*((R[i]-1)-(L[i]+1)+1))=max(h[i]*(R[i]-L[i]-1).(1<=i<=n)
若以寻常方法求L[i]、R[i],最坏情况复杂度是,若用单调栈求解的话复杂度是O(n)。
利用单调栈可以在O(n)时间内找到从左/右遍历第一个比它小/大的元素的位置
注意数据可能很大,用long long
AC代码:
1 #include<iostream> 2 #include<sstream> 3 #include<algorithm> 4 #include<string> 5 #include<cstring> 6 #include<iomanip> 7 #include<vector> 8 #include<cmath> 9 #include<ctime> 10 #include<stack> 11 #include<queue> 12 using namespace std; 13 int main() 14 { 15 ios::sync_with_stdio(false); 16 cin.tie(0);cout.tie(0); 17 int n; 18 long long h[100010]; 19 while(cin>>n&&n!=0) 20 { 21 for(int i=1;i<=n;i++) cin>>h[i]; 22 int L[100010],R[100010]; 23 stack<int> s; 24 for(int i=1;i<=n;i++)//利用单调栈求L[i] 25 { 26 while(!s.empty()&&h[i]<=h[s.top()]) s.pop(); 27 if(s.empty()) L[i]=0; 28 else L[i]=s.top(); 29 s.push(i); 30 } 31 while(!s.empty()) s.pop();//queue和stack都没有clear操作 32 for(int i=n;i>=1;i--)//利用单调栈求R[i] 33 { 34 while(!s.empty()&&h[i]<=h[s.top()]) s.pop(); 35 if(s.empty()) R[i]=n+1; 36 else R[i]=s.top(); 37 s.push(i); 38 } 39 //for(int i=1;i<=n;i++) cout<<L[i]<<' ';cout<<endl; 40 //for(int i=1;i<=n;i++) cout<<R[i]<<' ';cout<<endl; 41 long long ans=0; 42 for(int i=1;i<=n;i++) 43 ans=max(ans,h[i]*(R[i]-L[i]-1)); 44 cout<<ans<<endl; 45 } 46 47 } 48