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;
    }
    
    
  • 相关阅读:
    PDO扩展
    阿里云ECS VSFTP上传本地文件
    Nginx+lua_Nginx+GraphicsMagick来实现实时缩略图
    Mysql 5.6主从同步配置与解决方案
    windows安装配置mongodb及图形工具MongoVUE
    安装phpredis扩展以及phpRedisAdmin工具
    Redis安装配置以及开机启动
    CentOS安装Git服务器 Centos 6.5 + Git 1.7.1.0 + gitosis
    OpenStack 入门3
    Openstack 入门2
  • 原文地址:https://www.cnblogs.com/hezongdnf/p/12355753.html
Copyright © 2011-2022 走看看