hdu 1506 直方图内最大矩形

题目传送门//res tp hdu
单调栈的经典问题
维护区间的左右边界计算面积即可

#include<iostream>
#include<algorithm>
#include<stack>
using namespace std;
typedef long long ll;
const int L = 100010;
ll H[L];
int n;
ll Maxrectangle(){
	ll ans = 0;
	stack<int>M;
	for(int k = 1;k<=n;){
		if(M.empty()||H[M.top()] <=H[k])
			M.push(k++);
		else{
			ll h = H[M.top()];M.pop();
			if(M.empty())
				ans = max(ans,(k-1)*h);
			else
				ans = max(ans,(k-M.top()-1)*h);
		}
	}
	while(!M.empty()){
		ll h = H[M.top()];M.pop();
		if(M.empty())
			ans = max(ans,n*h);
		else
			ans = max(ans,(n-M.top())*h);
	}
	return ans;
}
int main(){
	while(scanf(" %d",&n)!=EOF&&n){
		for(int i = 1;i<=n;++i) cin>>H[i];
		ll ans = Maxrectangle();
		cout<<ans<<endl;
	}
	
}

原文地址:https://www.cnblogs.com/tea-egg/p/11268728.html