您的位置:首页 > 其它

POJ 2559 Largest Rectangle in a Histogram 【栈】

2017-09-23 20:41 295 查看
题目链接:http://poj.org/problem?id=2559

题意:有许多矩形,求其中连成最大矩形的面积。

题解:

这题真坑。

记 l[i] r[i] 为 以 i 为高度的建筑可以向左向右延展最长到哪里。

用栈维护,上一次所在的位置,如果栈顶元素所在建筑的高度 大于当前建筑高度,就延展。

但这样还是会被卡T,注意到相邻建筑只有连续两个,可以把 >= 抽成 > ,然后用一个 if 单独判断 == 的情况就可以了。

代码:

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <map> // STL
#include <string>
#include <vector>
#include <queue>
#include <stack>
#define mpr make_pair
#define debug() puts("okkkkkkkk")

using namespace std;

typedef long long LL;

const int inf = 1 << 26;

int n;
int a[300005];
int stk[300005];
int l[300005], r[300005];

int main(){
while( scanf("%d", &n), n ) {
int top = 0;
for ( int i = 1; i <= n; i ++ ) scanf("%d", &a[i]);

a[++ n] = -1;
for ( int i = 1; i <= n; i ++ ) {   // 对于每个 a[i] ,求这栋建筑高最多能延伸的长度 l[] 和 r[]
l[i] = r[i] = i;
while(top && a[stk[top]] > a[i]) {
l[i] = l[stk[top]];
r[stk[top]] = i-1;
-- top;
}

if (top && a[stk[top]] == a[i]) l[i] = l[stk[top]];
stk[++ top] = i;
}

LL res = 0;
for ( int i = 1; i < n; i ++ ) {
res = max(res, (r[i]-l[i]+1LL)*a[i]);
}

printf("%lld\n", res);
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: