Largest Rectangle in a Histogram

Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 33201 Accepted: 10817

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

题目大意:
给你n个矩形,宽都是1,高题目会给你,要你用O(n)求最大的面积。
思路:
想了半天结果还是被助攻了一下才过的,不过让我对单调栈又有了一层认知,单调栈再求连续的什么东西有出乎意料的妙处,他能过滤掉多余的没用的状态,剩下的全是有用的且呈一个递增或递减状态。
本题的思路,容易发现我们需要维护一个递增序列并且求maxarea,每次遇到一个比栈定小的元素说明栈里面的矩形面积已经是最大的了不可能再大了,因为你要和和你小的矩形合并那么之后的矩形只可能比之前更小而不会更大,所以我们出栈求maxarea。
这里其实还是可以想到的,但是没想到的是你不仅仅要维护高还要维护宽,因为栈定元素是最高的,那么栈顶下面的元素都可以横向与前面的元素组成一个新的面积(可能会产生更大的面积,样例就是这样的),因此我们每次遇到一个元素小于栈顶元素的时候都需要去维护一次栈里面的宽,并且把最大值求出来。一直这样操作最后maxarea就出来了。
另外还需要在增加一个push操作,原因是样例二,全部是相同元素需要一个0去取最大maxarea。

摘取到洛谷一段描述单调栈的话,我觉得把单调栈的特点完全体现出来了。
<mark>借助单调性处理问题的思想在于及时排除不可能的选项,保持策略集合的高度有效性和秩序性!</mark>

代码:

#include<iostream>
#include<algorithm>
using namespace std;

const int maxn=1e5+10;
typedef long long ll;
struct Stack{
	ll top;
	ll data[maxn];
	Stack(){
		top=0;
	}
	bool Isempty(){
		return top==0;
	}
};
ll ans;
ll width[maxn];
void push(Stack *&stack,ll x){
	if(stack->Isempty()||stack->data[stack->top]<x){
		stack->data[++stack->top]=x;
		width[stack->top]=1;
	}else{
		ll w=0;
		while(!stack->Isempty()&&x<=stack->data[stack->top]){
			w+=width[stack->top];
			ans=max(ans,w*stack->data[stack->top]);
			stack->top--;
		}
		stack->data[++stack->top]=x;
		width[stack->top]=w+1;
	}
}
int main(){
	int n;ll x;
	while(scanf("%d",&n)&&n){
		Stack *stack=new Stack();
		ans=0;
		for(int i=0;i<n;i++){
			scanf("%lld",&x);
			push(stack,x);
		}
		push(stack,0);
		printf("%lld\n",ans);
	}
}