您的位置:首页 > 其它

[POJ 2559 Largest Rectangle in a Histogram] 单调栈

2016-08-26 11:39 309 查看

[POJ 2559 Largest Rectangle in a Histogram] 单调栈

题目链接[POJ 2559 Largest Rectangle in a Histogram]

题意描述:给定一个柱形图,总长度为N,每个区间长度为h1,h2,…,hn,求在柱形图中的最大面积的矩形。



解题思路

点击查看单调栈的一些性质:《 [poj 2796 Feel Good] 单调栈

单调栈求出每个数向左向右能够拓展的最大区间,然后乘以区间长度就好了。

#include <stack>
#include <queue>
#include <cmath>
#include <cstdio>
#include <string>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;

//#pragma comment(linker, "/STACK:1024000000,1024000000")

#define FIN             freopen("input.txt","r",stdin)
#define FOUT            freopen("output.txt","w",stdout)
#define fst             first
#define snd             second

typedef __int64 LL;
//typedef long long LL;
typedef pair<int, int> PII;

const int MAXN = 100000 + 5;
const int INF = 0x3f3f3f3f;
int N;
int H[MAXN], L[MAXN], R[MAXN];
struct SNode {
int id, val;
SNode () {}
SNode (int id, int val) : id (id), val (val) {}
} tp;
stack<SNode> stk;
int main() {
#ifndef ONLINE_JUDGE
FIN;
#endif // ONLINE_JUDGE
while (~scanf ("%d", &N) && N) {
int P = 0;
for (int i = 1; i <= N; i++) {
scanf ("%d", &H[i]);
}
for (int i = 1; i <= N; i++) {
while (!stk.empty() && stk.top().val > H[i]) {
tp = stk.top();
R[tp.id] = i - 1;
stk.pop();
}
stk.push (SNode (i, H[i]) );
}
while (!stk.empty() ) {
tp = stk.top();
R[tp.id] = N;
stk.pop();
}
for (int i = N; i >= 1; i--) {
while (!stk.empty() && stk.top().val > H[i]) {
tp = stk.top();
L[tp.id] = i + 1;
stk.pop();
}
stk.push (SNode (i, H[i]) );
}
while (!stk.empty() ) {
tp = stk.top();
L[tp.id] = 1;
stk.pop();
}
LL ans = -1;
int l, r;
for (int i = 1; i <= N; i++) {
LL x = (LL) (R[i] - L[i] + 1) * H[i];
if (x >= ans) {
ans = x, l = L[i], r = R[i];
}
}
printf ("%I64d\n", ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: