zoukankan      html  css  js  c++  java
  • hdu 1506 Largest Rectangle in a Histogram

      这道题的题意很简单,看图就可以搞定了。

      思路:维护一个单调递增的栈,为什么要这样做呢。因为高度越小的柱形在算面积的时候肯定在宽度方面要占优吧,也算是避免算不到高度小却宽度大的长方形,所以要这样做。这样当当前柱形的高度小于栈顶柱形的高度的时候就把小于当前柱形高度的指针弹出,与此同时计算一下所有比它高的柱形的面积和。然后把当前柱形与弹出栈的柱形合并成一个柱形,宽度是好几个1,高度是当前柱形的高度,然后再压入栈。ps:最后这个想法不是我的,我想到要弹栈那里就不会了,是参考网上大牛的,具体来源我找了下,没找到,不好意思。下面是代码:

    View Code
    #include <algorithm>
    #include <iostream>
    #include <cstdlib>
    #include <cstring>
    #include <cstdio>
    
    using namespace std;
    
    const int maxn=100000+5;
    
    int top,n;
    
    struct node
    {
        int val;
        __int64 width;
    }stack[maxn];
    
    void push(int x,int y)
    {
        top++;
        stack[top].val=x;
        stack[top].width=y;
    }
    
    __int64 max(__int64 x,__int64 y)
    {
        return x<y?y:x;
    }
    
    int main()
    {
        int n,h,x,y;
        __int64 ans;
        while(scanf("%d",&n),n)
        {
            ans=top=0;
            for(int i=1;i<=n+1;i++)
            {
                if(i==n+1) h=0;
                else scanf("%d",&h);
                if(!top||h>=stack[top].val)
                    push(h,1);
                else
                {
                    __int64 cnt=0;
                    while(top>0&&h<stack[top].val)
                    {
                        int p=stack[top].val;
                        int q=stack[top].width;
                        __int64 tmp=p*(cnt+q);
                        ans=max(ans,tmp);
                        cnt+=q;
                        top--;
                    }
                    push(h,cnt+1);
                }
            }
            printf("%I64d\n",ans);
        }
        return 0;
    }

    具体的部分思路中已经说明。acmer加油!

    善待每一天,努力做好自己。

    欢迎转载,注明出处。

  • 相关阅读:
    SpringBoot异步处理请求
    5本最佳的 Java 面向对象理论和设计模式的书籍
    彻底弄懂 HTTP 缓存机制 —— 基于缓存策略三要素分解法
    Java 性能优化的五大技巧
    Java 8 最佳技巧
    Java 并发的四种风味:Thread、Executor、ForkJoin 和 Actor
    在 Java 8 中避免 Null 检查
    关于创建java线程池问题的思考
    LuoguP1858 多人背包(DP)
    Luogu[YNOI2019]排序(DP,线段树)
  • 原文地址:https://www.cnblogs.com/RainingDays/p/3067606.html
Copyright © 2011-2022 走看看