单调栈
#include <iostream>
#include "cstring"
#include "stack"
using namespace std;
struct t
{
int w;
int h;
};
struct t a[1005];
int main()
{
int n;
cin >> n;
int max;
for (int i = 0; i < n; i++)
{
cin >> a[i].h;
a[i].w = 1;
}
a[n].h = 0;
stack<t> b;
max = a[0].h;
for (int i = 0; i <= n; i++)
{
if (b.empty())
b.push(a[i]);
else if (a[i].h >= b.top().h)
b.push(a[i]);
else
{
int num = 0;
while (!b.empty())
{
if(a[i].h >= b.top().h)break;
int temp = b.top().h*(b.top().w+num);
if (temp > max)
max = temp;
num+=b.top().w;
b.pop();
}
a[i].w+=num;
b.push(a[i]);
}
}
cout << max << endl;
return 0;
}
本文深入探讨了单调栈算法的实现细节,通过一个具体的C++代码示例,展示了如何使用单调栈来解决最大矩形面积的问题。该算法适用于处理一系列元素,当需要找到每个元素左侧或右侧最近的较小元素时特别有效。

被折叠的 条评论
为什么被折叠?



