poj 2559(单调栈)
来源:互联网 发布:阿里云到底是什么 编辑:程序博客网 时间:2024/05/16 08:45
题意:给出了一个矩形图,求出最大的长方形面积。
如果确定长方形的左端点L和右端点R,那么最大可能的高度就是min(hi|L<=i<R),于是可以得到一个o(n^3)的算法,如果对区间高度的最小值进行预处理,可以降到o(n^2),但复杂度还是高了,有没有更好的方法呢?单调栈。
考虑一个面积最大的长方形,它的左端点是L,右端点是R,高度是H,那么必有h(L-1)<H,否则就可以扩展左端点,得到一个更大的长方形,同理,有h(R)<H。这样,我们可以对每一个h(i),求出它的L(i)和R(i),L(i)表示:j<=i且h(j)<=h(i)的最大的j,即从i向左扩展到比h(i)小的第一个下标;R(i)表示:j>i且h(j)<h(i)的最小的j,即从i向右扩展到比h(i)小的第一个下标。
明确L(i)和R(i)的含义后,用单调栈就可以高效的求得。所求最大面积就是max(h(i)*(R(i)-L(i)))。
代码如下:
#include <cstdio>#include <stack>#include <set>#include <iostream>#include <string>#include <vector>#include <queue>#include <functional>#include <cstring>#include <algorithm>#include <cctype>#include <string>#include <map>#include <iomanip>#include <cmath>#define LL long long#define ULL unsigned long long#define SZ(x) (int)x.size()#define Lowbit(x) ((x) & (-x))#define MP(a, b) make_pair(a, b)#define MS(arr, num) memset(arr, num, sizeof(arr))#define PB push_back#define F first#define S second#define ROP freopen("input.txt", "r", stdin);#define MID(a, b) (a + ((b - a) >> 1))#define LC rt << 1, l, mid#define RC rt << 1|1, mid + 1, r#define LRT rt << 1#define RRT rt << 1|1#define BitCount(x) __builtin_popcount(x)#define BitCountll(x) __builtin_popcountll(x)#define LeftPos(x) 32 - __builtin_clz(x) - 1#define LeftPosll(x) 64 - __builtin_clzll(x) - 1const double PI = acos(-1.0);const int INF = 0x3f3f3f3f;using namespace std;const int N=100010;const double eps = 1e-8;const int MAXN = 300 + 10;const int MOD = 1000007;const int dir[][2] = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} };typedef pair<int, int> pii;int n,m,st[N],h[N],L[N],R[N];int main(){ int i,j; while(~scanf("%d",&n),n) { for (i=0;i<n;i++) scanf("%d",h+i); int top=0; for (i=0;i<n;i++) { // L(i) while(top>0 && h[st[top-1]]>=h[i]) top--; L[i]=top==0?0:st[top-1]+1; st[top++]=i; } top=0; for (i=n-1;i>=0;i--){ <span style="font-family: Arial, Helvetica, sans-serif;">// R(i)</span> while(top>0 && h[st[top-1]]>=h[i]) top--; R[i]=top==0?n:st[top-1]; st[top++]=i; } LL ans=0; // 防止溢出 for (i=0;i<n;i++) { ans=max(ans,(LL)h[i]*(R[i]-L[i])); } cout<<ans<<endl; }}
0 0
- POJ 2559 单调栈
- POJ 2559 单调栈
- poj 2559(单调栈)
- poj 2559 单调栈
- POJ 2559 单调栈
- poj 2559 单调栈
- poj 2559 单调栈
- POJ 2559 单调栈 Histogram
- poj 2559(单调栈)
- 单调栈(poj -- 2559)
- POJ 2559 单调栈模板
- POJ 2559 单调栈模板题
- POJ - 2559(单调栈入门题)
- 【单调栈】POJ 3250
- poj 2796#单调栈
- POJ 2796 单调栈~
- poj 2796(单调栈)
- poj 2059 单调栈
- 线程死锁问题
- ASP.NET的JSON序列化与反序列化
- HTTP协议详解
- OGRE Review of 2014
- 图像处理之 YUYV422 To OpenCV IplImage
- poj 2559(单调栈)
- 2015_1_15调研总结
- 实例讲解SQL注入攻击 http://www.csdn.net/article/2015-01-13/2823533-SQL?reload=1 作者zer0Black
- OPENCV 测试Mat
- 不使用第三方变量来交换两个变量的值
- Error与Exception有什么区别?
- mysql 有可能的优化方式
- The Miner - Flash项目性能测试器
- Ogre3D based “NeoAxis” game engine now free