单调栈--poj2559 Largest rectangle in a Histogram

来源:互联网 发布:开淘宝店怎么发货 编辑:程序博客网 时间:2024/05/21 06:41

一个直方图里,求最大的矩形。类似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;

}

阅读全文
0 0
原创粉丝点击