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);
  • 相关阅读:
    c++ STL
    unix network programming(3rd)Vol.1 [第1章]《读书笔记系列》
    [面试题] BloomFilter 无序40亿不重复 uint 整数, 给予任意的数,求是否在这40亿之中 + 无序数组中找2个相同的值
    stm32 DAC输出音频
    Go语言项目的错误和异常管理 via 达达
    值传递
    FireFox、chrome通过插件使用IE内核,IE Tab v2
    linux cross toolsChain 交叉编译 ARM(转)
    rfc all download
    VS2005 工程在win7下使用管理员权限运行
  • 原文地址:https://www.cnblogs.com/Cindy-Chan/p/11191664.html
Copyright © 2011-2022 走看看