您的位置:首页 > 其它

51Nod - 1102 单调栈

2017-02-03 22:22 197 查看

题意:

有一个正整数的数组,化为直方图,求此直方图包含的最大矩形面积。例如 2,1,5,6,2,3,对应的直方图如下:



面积最大的矩形为5,6组成的宽度为2的矩形,面积为10。

Input
第1行:1个数N,表示数组的长度(0 <= N <= 50000)
第2 - N + 1行:数组元素A[i]。(1 <= A[i] <= 10^9)


Output
输出最大的矩形面积


Input示例
6
2
1
5
6
2
3


Output示例
10


思路:

单调栈的模板题,枚举最低点,然后找到左右的边界。

代码:

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MAXN = 5e4 + 10;

ll a[MAXN];
int l[MAXN], r[MAXN];

int main() {
int n;
scanf("%d", &n);
for (int i = 1; i <= n; i++)
scanf("%I64d", &a[i]);
stack <int> sta;
for (int i = 1; i <= n; i++) {
while (!sta.empty() && a[sta.top()] >= a[i]) sta.pop();
l[i] = sta.empty() ? 0 : sta.top();
sta.push(i);
}
while (!sta.empty()) sta.pop();
for (int i = n; i >= 1; i--) {
while (!sta.empty() && a[sta.top()] >= a[i]) sta.pop();
r[i] = sta.empty() ? n + 1 : sta.top();
sta.push(i);
}
ll ans = 0;
for (int i = 1; i <= n; i++)
ans = max(ans, (r[i] - l[i] - 1) * a[i]);
printf("%I64d\n", ans);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  51Nod acm 单调栈