• [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);
  • 相关阅读:
    【CSS学习】--- 背景
    线程运行诊断
    Mysql变量、存储过程、函数、流程控制
    设计模式之外观模式(门面模式)
    Spring的JdbcTemplate使用教程
    @AspectJ注解的value属性
    自定义Yaml解析器替换Properties文件
    @Import导入自定义选择器
    Spring中Bean命名源码分析
    Java操作fastDFS
  • 原文地址:https://www.cnblogs.com/Cindy-Chan/p/11191664.html
Copyright © 2020-2023  润新知