zoukankan      html  css  js  c++  java
  • 单调栈

    Problem Description

    hdu-1506
    A histogram is a polygon composed of a sequence of rectangles aligned at a common base line. The rectangles have equal widths but may have different heights. For example, the figure on the left shows the histogram that consists of rectangles with the heights 2, 1, 4, 5, 1, 3, 3, measured in units where 1 is the width of the rectangles:

    Usually, histograms are used to represent discrete distributions, e.g., the frequencies of characters in texts. Note that the order of the rectangles, i.e., their heights, is important. Calculate the area of the largest rectangle in a histogram that is aligned at the common base line, too. The figure on the right shows the largest aligned rectangle for the depicted histogram.

    Analysis of ideas

    求这个图形可以组成的最大的矩形的面积
    如果我们枚举每一个点,再枚举左边和右边可以扩展的长度,那么时间复杂度是 (O(n^2))
    如果把左边和右边可以扩展的长度预处理出来,就可以在 (O(n)) 的时间内解决了

    Accepted code

    #include <bits/stdc++.h>
    using namespace std;
    #define ll long long
    const int maxn = 100100;
    ll a[maxn];
    int l[maxn],r[maxn];
    stack <int> s;
    
    int main()
    {
        int n;
        while(cin>>n && n)
        {
            for(int i = 1; i <= n; i++)
            {
                scanf("%lld",&a[i]);
            }
            while(!s.empty())
                s.pop();
            for(int i = 1; i <= n; i++)
            {
                while(!s.empty() && a[s.top()] >= a[i])
                    s.pop();
                if(s.empty())
                    l[i] = 1;
                else
                    l[i] = s.top()+1;
                s.push(i);
            }
            while(!s.empty())
                s.pop();
            for(int i = n; i >= 1; i--)
            {
                while(!s.empty() && a[i] <= a[s.top()])
                    s.pop();
                if(s.empty())
                    r[i] = n+1;
                else
                    r[i] = s.top();
                s.push(i);
            }
            ll ans = 0;
            for(int i = 1; i <= n; i++)
            {
                ans = max(ans,a[i]*(r[i]-l[i]));
            }
            printf("%lld
    ",ans);
        }
        return 0;
    }
    
    
  • 相关阅读:
    css 伪类
    tornado 作业 简单首页 登录页 个人中心
    tornado 作业 自定义模板 UIMethod以UIModule
    tornado 网页提交内容 展示内容作业
    tornado
    javascript
    廖雪峰官网学习js 数组
    廖雪峰官网学习js 字符串
    廖雪峰官网学习js 数据类型和变量
    协程gevent学习
  • 原文地址:https://www.cnblogs.com/hezongdnf/p/12355753.html
Copyright © 2011-2022 走看看