zoukankan      html  css  js  c++  java
  • [POJ 2559]Largest Rectangle in a Histogram 单调栈

    Largest Rectangle in a Histogram

    Description

    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.

    Input

    The input contains several test cases. Each test case describes a histogram and starts with an integer n, denoting the number of rectangles it is composed of. You may assume that 1<=n<=100000. Then follow n integers h1,...,hn, where 0<=hi<=1000000000. These numbers denote the heights of the rectangles of the histogram in left-to-right order. The width of each rectangle is 1. A zero follows the input for the last test case.

    Output

    For each test case output on a single line the area of the largest rectangle in the specified histogram. Remember that this rectangle must be aligned at the common base line.

    Sample Input

    7 2 1 4 5 1 3 3
    4 1000 1000 1000 1000
    0
    

    Sample Output

    8
    4000

    分析:

    判断一个不规则图形中最大矩形面积的方法是什么呢?

    如果这是一个单调递增的图案,那么几种情况如下图

    如果不是,那么我们就将其转化为单调递增的图案:

    可以想到把所有的高度维持在一个单调递增的栈中,pop()时维持每个方块的宽度。

     代码片段如下:

    for(int i = 1; i <= n; i++)
        scanf("%d",&k[i]);
               
    k[n + 1] = 0;
    n++;    
            
     for(int i = 1; i <= n; i++)
    {
        if(h.empty() || k[i] >= h.top())//入栈条件 
        h.push(k[i]),w.push(1);
        //若将入栈的图案高度小于此时top的高度,为了维持单调性,要将高于当前图案的出栈 
        else
        {
            t = 0;
            while(!h.empty() && h.top() > k[i])//记得注意若栈已经空了则不再出栈 
            { 
                t += w.top();//存储出栈的个数作为宽度 
                if(t * h.top() > S)S = t * h.top();//出栈时计算可形成的最大面积 
                        h.pop();
                        w.pop();
            }    
            h.push(k[i]);
            w.push(t + 1);//加上新入图形的宽度 
        }
    }
            
    printf("%lld
    ",S);
  • 相关阅读:
    zblog如何更改数据库配置以及生效
    阿里云RDS数据库改造迁移方案
    如何突破微信的支付额度限制
    IIS进行URL重写——实现https重定向,文件类型隐藏访问重写,nodejs等服务重写等等
    windows设置本地域名解析
    自己写的加密网页,与百度网盘私密很相似,需要密码才能访问(原创)
    CSS3 translate、transform、transition区别
    IIS前端页面不显示详细错误解决方法
    CSS滚动条设置
    IIS支持PHP文件解析
  • 原文地址:https://www.cnblogs.com/Cindy-Chan/p/11191664.html
Copyright © 2011-2022 走看看