poj 2559(单调栈)

本文介绍了一种利用单调栈优化矩形最大面积查找算法的方法,将时间复杂度从O(n^3)降低至O(n^2),并通过代码实现详细解释了算法过程。

       题意:给出了一个矩形图,求出最大的长方形面积。

      如果确定长方形的左端点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) - 1
const 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;
    }
}


















评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值