zoukankan      html  css  js  c++  java
  • POJ 2559 Largest Rectangle in a Histogram(单调栈)

    题意:有n个高度不同的直方图,求直方图内最大的矩形面积。

    分析:

    1、若当前研究高度大于栈顶高度,则直接入栈。否则,边处理栈内所有高度大于等于当前高度的元素边出栈,在此过程中,边累加宽度边以当前栈顶元素为高算出矩形面积,比较最大值,直到最终将比当前高度大的元素都捋平,将捋平后的高度即当前高度,和最终累积的宽度入栈。

    2、上述处理的结果,使得栈内所剩的元素都是从栈顶到栈底高度递减,按照与1相同的处理方法计算栈内元素的矩形面积,比较最大值即可。

    #pragma comment(linker, "/STACK:102400000, 102400000")
    #include<cstdio>
    #include<cstring>
    #include<cstdlib>
    #include<cctype>
    #include<cmath>
    #include<iostream>
    #include<sstream>
    #include<iterator>
    #include<algorithm>
    #include<string>
    #include<vector>
    #include<set>
    #include<map>
    #include<stack>
    #include<deque>
    #include<queue>
    #include<list>
    #define Min(a, b) ((a < b) ? a : b)
    #define Max(a, b) ((a < b) ? b : a)
    const double eps = 1e-8;
    inline int dcmp(double a, double b){
        if(fabs(a - b) < eps) return 0;
        return a > b ? 1 : -1;
    }
    typedef long long LL;
    typedef unsigned long long ULL;
    const int INT_INF = 0x3f3f3f3f;
    const int INT_M_INF = 0x7f7f7f7f;
    const LL LL_INF = 0x3f3f3f3f3f3f3f3f;
    const LL LL_M_INF = 0x7f7f7f7f7f7f7f7f;
    const int dr[] = {0, 0, -1, 1, -1, -1, 1, 1};
    const int dc[] = {-1, 1, 0, 0, -1, 1, -1, 1};
    const int MOD = 1e9 + 7;
    const double pi = acos(-1.0);
    const int MAXN = 100000 + 10;
    const int MAXT = 10000 + 10;
    using namespace std;
    struct Node{
        int h, w;
        Node(){}
        Node(int hh, int ww):h(hh), w(ww){}
    }num[MAXN];
    stack<Node> s;
    int main(){
        int n;
        while(scanf("%d", &n) == 1){
            if(!n) return 0;
            for(int i = 0; i < n; ++i){
                scanf("%d", &num[i].h);
            }
            LL ans = 0;
            for(int i = 0; i < n; ++i){
                int width = 0;
                while(!s.empty() && s.top().h >= num[i].h){
                    int tmph = s.top().h;
                    int tmpw = s.top().w;
                    s.pop();
                    width += tmpw;
                    ans = Max(ans, (LL)tmph * width);
                }
                s.push(Node(num[i].h, width + 1));
            }
            int t = 0;
            while(!s.empty()){
                Node tmp = s.top();
                s.pop();
                ans = Max(ans, (LL)tmp.h * (t + tmp.w));
                t += tmp.w;
            }
            printf("%lld\n", ans);
        }
        return 0;
    }
    

      

  • 相关阅读:
    swift textfiled 输入完毕 return 隐藏键盘 方法
    第一篇,仅是为了纪念
    ASP.NET MVC之验证终结者篇
    ASP.NET MVC扩展之HtmlHelper辅助方法
    Java历程-初学篇 Day04选择结构(1)
    Java历程-初学篇 Day03扫描仪与类型转换
    Java历程-初学篇 Day02变量,数据类型和运算符
    Java历程-初学篇 Day01初识java
    简单工厂模式和策略模式理解
    工厂模式和策略模式的区别
  • 原文地址:https://www.cnblogs.com/tyty-Somnuspoppy/p/6547291.html
Copyright © 2011-2022 走看看