本文主要是介绍单调栈--poj2559 Largest rectangle in a Histogram,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一个直方图里,求最大的矩形。类似2 1 4 5 1 3 3
做完poj2796,再回来看,其实就是区间最小值乘区间长度吧。
解释见 http://blog.csdn.net/alongela/article/details/8230739
#include <iostream>
#include <cstdio>
#include <cstring>
#include <stack>
using namespacestd;
const int maxn =100000 +5;
int h[maxn],dep[maxn];
typedef pair<int,int> pr;//记录矩形的高度,宽度
int main()
{
int n;
while(scanf("%d",&n) !=EOF && n)
{
memset(h,0,sizeof(h));
memset(dep,0,sizeof(dep));
for (int i =1; i <= n; i ++) {
scanf("%d",&h[i]);//1e9
}
stack<pr> stk;
longlong area =0;
int t =0;
for (int i =1; i <= n; i ++) {
while (!stk.empty() && stk.top().first >= h[i]) {
area = max(area,(longlong)stk.top().first * (stk.top().second + t));
t += stk.top().second;
stk.pop();
}
stk.push({h[i],t +1});
t = 0;
}
t = 0;
while (!stk.empty()) {
area = max(area,(longlong)stk.top().first * (stk.top().second + t));
t += stk.top().second;
stk.pop();
}
printf("%lld\n",area);
}
return0;
}
这篇关于单调栈--poj2559 Largest rectangle in a Histogram的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!