HDU-1506-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

题解:

利用单调栈,可以找到从左/右遍历第一个比它小/大的元素的位置

这个题需要向左和向右遍历两次,如果暴力的话是要超的,所以可以利用单调栈把复杂度降到O(n)

注意每次用前先把栈清空,不然会因为之前的数据对当前造成影响

代码:

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<stack>

using namespace std;

int main() {
	int n;
	stack<int>s;
	long long int a[100005];
	long long int L[100005];
	long long int R[100005];
	while(~scanf("%d",&n)&&n) {
		for(int t=0; t<n; t++) {
			scanf("%I64d",&a[t]);
		}
		while(s.size()) s.pop();//清空栈 
		for(int t=0; t<n; t++) {
			while(s.size()&&a[s.top()]>=a[t]) {
				s.pop();
			}
			if(s.empty())
				L[t]=0;
			else
				L[t]=s.top()+1;
			s.push(t);
		}
		while(s.size()) s.pop();//清空栈
		for(int t=n-1; t>=0; t--) {
			while(s.size()&&a[s.top()]>=a[t]) {
				s.pop();
			}
			if(s.empty())
				R[t]=n;
			else {
				R[t]=s.top();
			}
			s.push(t);
		}
		long long int maxn=0;
		for(int t=0; t<n; t++) {
			maxn=max(maxn,a[t]*(R[t]-L[t]));
		}
		printf("%I64d
",maxn);
	}
	return 0;
}
原文地址:https://www.cnblogs.com/Staceyacm/p/10781979.html