您的位置:首页 > 其它

单调栈--poj2559 Largest rectangle in a Histogram

2017-07-26 10:19 435 查看
一个直方图里,求最大的矩形。类似2 1 4 5 1 3 3

做完poj2796,再回来看,其实就是区间最小值乘区间长度吧。

解释见 http://blog.csdn.net/alongela/article/details/8230739

#include <iostream>

#include <cstdio>

#include <cstring>

#include <stack>

using namespacestd;

const int maxn =100000 +5;

int h[maxn],dep[maxn];

typedef pair<int,int> pr;//记录矩形的高度,宽度

int main()

{

    int n;

    while(scanf("%d",&n) !=EOF
&& n)

    {

        memset(h,0,sizeof(h));

        memset(dep,0,sizeof(dep));

        for (int i =1; i <= n; i ++) {

            scanf("%d",&h[i]);//1e9

        }

        stack<pr> stk;

        longlong area =0;

        int t =0;

        for (int i =1; i <= n; i ++) {

                while (!stk.empty() && stk.top().first
>= h[i]) {

                    area = max(area,(longlong)stk.top().first
* (stk.top().second + t));

                    t += stk.top().second;

                    stk.pop();

                }

                 stk.push({h[i],t +1});

            t = 0;

        }

        t = 0;

        while (!stk.empty()) {

            area = max(area,(longlong)stk.top().first
* (stk.top().second + t));

            t += stk.top().second;

            stk.pop();

        }

        printf("%lld\n",area);

    }

    return0;

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