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 单独判断 == 的情况就可以了。
代码:
题意:有许多矩形,求其中连成最大矩形的面积。
题解:
这题真坑。
记 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; }
相关文章推荐
- poj 2559 Largest Rectangle in a Histogram
- POJ 2559 Largest Rectangle in a Histogram -- 动态规划
- POJ 2559 -- Largest Rectangle in a Histogram ( 单调栈 )
- POJ 2559 Largest Rectangle in a Histogram 单调栈学习
- poj 2559 Largest Rectangle in a Histogram
- POJ2559-Largest Rectangle in a Histogram
- poj2559——Largest Rectangle in a Histogram
- POJ - 2559 Largest Rectangle in a Histogram (单调栈与区间问题)
- 【POJ 2559】Largest Rectangle in a Histogram
- 【单调栈】POJ-2559 Largest Rectangle in a Histogram
- POJ 2559 Largest Rectangle in a Histogram
- Largest Rectangle in a Histogram(POJ-2559)
- POJ 2559 Largest Rectangle in a Histogram(单调栈)
- poj 2559 Largest Rectangle in a Histogram
- POJ 2559 Largest Rectangle in a Histogram ——笛卡尔树
- HDU 1506 && POJ 2559 Largest Rectangle in a Histogram (单调队列)
- POJ2559 Largest Rectangle in a Histogram —— 单调栈
- POJ 2559 Largest Rectangle in a Histogram【单调栈】
- [poj 2559] Largest Rectangle in a Histogram:单调栈
- poj2559 & zoj1985 &hdu1506 Largest Rectangle in a Histogram(笛卡尔树)