POJ2082 Terrible Sets(单调栈)
来源:互联网 发布:赫鲁晓夫 知乎 编辑:程序博客网 时间:2024/06/07 03:21
题意:给出n个矩形的长和宽,它们挨着排列在x轴上,求能够构成的最大矩形的面积。
思路:多个矩阵拼起来的矩形最大高度取决于最短的那个小矩形,使用两次单调栈处理出每个小矩形左右两个方向上最近的一个比这个矩形矮的矩形的位置, 即确定了当前矩形能向左右两边延伸的最远距离。然后按照矩形的高度从低到高,算出来每个矩形高度能得到的最大面积,取最大值即可。
#include<iostream>#include<cstdio>#include<cstring>#include<cmath>#include<cstdlib>#include<algorithm>using namespace std;typedef long long ll;const int inf = 0x3f3f3f3f;const int mod = 1000000007;const int maxn = 50005;const int N = 100005;struct node{ int h,w,l,r,pos; /*矩形的高、宽、向左的边界、向右的边界、初始下标*/ bool operator < (const node &b) const{ return h < b.h; }}rec[maxn];int len[maxn];int main(){ int n,ddStack[maxn]; while(~scanf("%d",&n) && n != -1){ len[0] = 0; for(int i=0; i<n; ++i){ scanf("%d%d", &rec[i].w, &rec[i].h); rec[i].l = 0; rec[i].r = n; rec[i].pos = i; len[i + 1] = len[i] + rec[i].w; } /*两次单调栈维护左右两个方向*/ int pos = 0; for(int i=0; i<n; ++i){ if(pos == 0 || rec[i].h >= rec[ddStack[pos - 1]].h){ ddStack[pos++] = rec[i].pos; } else { while(pos >= 1 && rec[ddStack[pos - 1]].h > rec[i].h){ rec[ddStack[pos - 1]].r = i; --pos; } ddStack[pos++] = rec[i].pos; } } pos = 0; for(int i=n-1; i>=0; --i){ if(pos == 0 || rec[i].h >= rec[ddStack[pos - 1]].h){ ddStack[pos++] = rec[i].pos; } else { while(pos >= 1 && rec[ddStack[pos - 1]].h > rec[i].h){ rec[ddStack[pos - 1]].l = i + 1; --pos; } ddStack[pos++] = rec[i].pos; } } sort(rec, rec + n); int ans = 0, now = 0; for(int i=0; i<n; ++i){ now = rec[i].h * (len[rec[i].r] - len[rec[i].l]); if(now > ans)ans = now; } printf("%d\n",ans); } return 0;}
阅读全文
0 0
- POJ2082 Terrible Sets(单调栈)
- poj2082 Terrible Sets 单调栈
- POJ2082---Terrible Sets(单调栈)
- POJ2082 Terrible Sets [DP 单调栈]
- poj2082(Terrible Sets单调栈入门题)
- POJ2082--Terrible Sets(栈)
- poj2082----Terrible Sets(处女座单调栈求区间问题)
- poj2082 Terrible Sets
- POJ 2082 Terrible Sets(单调栈)
- POJ-2082 Terrible Sets (单调栈)
- 【POJ】2082 - Terrible Sets(单调栈)
- poj_2082 Terrible Sets(单调栈)
- poj 2082 Terrible Sets (单调栈)
- Terrible Sets *---* 单调栈解决问题
- Terrible Sets (单调队列)
- Terrible Sets (单调队列)
- Terrible Sets--(单调队列)
- poj2082(单调栈)
- 关于排序
- java学习初探1
- 2017年7月-占位3
- CodeForces822C【贪心】
- HDU
- POJ2082 Terrible Sets(单调栈)
- 安装 magenta 失败:rtmidi
- Python3中的PyMongo如何使用?
- JDBC
- springmvc学习笔记3
- Web跨域分析与解决
- http问题
- Linux 下使用C++监测某一进程的状态
- 详解Promise的含义