首页 > 其他 > 详细

单调栈

时间:2020-02-24 12:54:09      阅读:61      评论:0      收藏:0      [点我收藏+]

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\n",ans);
    }
    return 0;
}

单调栈

原文:https://www.cnblogs.com/hezongdnf/p/12355753.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!