HDU-1506 Largest Rectangle in a Histogram

来源:互联网 发布:网络教研课题结项 编辑:程序博客网 时间:2024/06/08 19:15

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 34 1000 1000 1000 10000
Sample Output
84000

思路:当然是枚举啦,不过重点在于枚举什么呢?? 

 仔细想一想面积最大的时候是什么情况,没错就是题目中的第二张图那样,(不是图越高越好哦!!!)

所以呢,我们就从一个直方图开始,往两边开始找比他高的图,,,。说到这里,dp还是没用到啊,不过你先这样写试试,绝对送你一个“”超时“”大礼包。那我们怎么办呢?想想看,我们枚举每一个点,都要重新刷一遍,其实某些点已经刷过了,这些点重新刷造成了超时。。。

比如,1<2<3<4>5图,我们刷2时,还要判断2<3<4吗,不用!!!1已经刷过了,2没有必要。用以一个数组记录r[1]=4。然后a[r[i]-1]判断,就省略了好多。

代码如下:

#include<stdio.h>#define N 100100__int64 a[N],l[N],r[N],n;//求和第i个木板连续的高于或等于它的最左边木板和最右边木板,i,j,然后面积s=(j-i+1)*s[i],求最大的s即可.int main(){    while(~scanf("%d",&n)&&n)    {        for(int i=1;i<=n;i++)            scanf("%I64d",&a[i]);        l[1]=1;        r[n]=n;        for(int i=1;i<=n;i++)        {            int t=i;//求和第i个木板连续的高于或等于它的最左边的木板.            while(t>1&&a[t-1]>=a[i])                t=l[t-1];            l[i]=t;        }        for(int i=n;i>=0;i--)        {            int t=i;//求和第i个木板连续的高于或等于它的最右边的木板.            while(t<n&&a[t+1]>=a[i])                t=r[t+1];            r[i]=t;        }         __int64 max=0;        for(int i=1;i<=n;i++)        {            if((r[i]-l[i]+1)*a[i]>max)                max=(r[i]-l[i]+1)*a[i];        }        printf("%I64d\n",max);    }    return 0;}


原创粉丝点击