• 单调栈


    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;
    }
    
    
  • 相关阅读:
    阿里双11,如何实现每秒几十万的高并发写入
    记住:永远不要在 MySQL 中使用 UTF-8
    史上最烂的项目:苦撑 12 年,600 多万行代码
    除了不要 SELECT * ,使用数据库还应知道的11个技巧!
    厉害了,为了干掉 HTTP ,Spring团队又开源 nohttp 项目!
    请停止学习框架
    基于 MySQL 主从模式搭建上万并发的系统架构
    JS获取节点
    JS函数
    JS
  • 原文地址:https://www.cnblogs.com/hezongdnf/p/12355753.html
Copyright © 2020-2023  润新知