hdu 1506-Largest Rectangle in a Histogram

来源:互联网 发布:淘宝直播伴侣 编辑:程序博客网 时间:2024/06/06 02:47

题目链接:  http://acm.hdu.edu.cn/showproblem.php?pid=1506


题目描述:

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 34 1000 1000 1000 10000

Sample Output

84000

题目大意:

给你n块木板以及每块木板的高度,叫你找出当中面积最大的矩形


思路:

这一题的思路是算出每一个小矩阵所能代表的最大面积,通过找出左右两边连续的比该矩阵高度要高的最远矩阵的下表得到底边长,在与该矩阵的高做积得到结果!(详见代码中的注释)

AC代码:

#include<iostream>#include<cstdlib>#include<cmath>#include<cstring>#include<cstdio>using namespace std;long long int l[100005],r[100005],a[100005];int main(){    long long int n,i,j,sign;    while(scanf("%lld",&n),n)    {        for(i=1;i<=n;i++)            scanf("%lld",&a[i]);        memset(l,0,sizeof(l));//l数组是记录a[i]左边连续比a[i]高的矩阵的下标        memset(r,0,sizeof(r));//r数组是记录a[i]右边连续比a[i]高的矩阵的下标        l[1]=1;        r[n]=n;        for(i=2;i<=n;i++)        {            sign=i;            while(sign>1&&a[i]<=a[sign-1])                sign=l[sign-1];            l[i]=sign;        }        for(i=n-1;i>=1;i--)        {            sign=i;            while(sign<n&&a[i]<=a[sign+1])                sign=r[sign+1];            r[i]=sign;        }        long long int Max=0;        for(i=1;i<=n;i++)        {            Max=max(Max,(r[i]-l[i]+1)*a[i]);        }        printf("%lld\n",Max);    }    return 0;}



0 0
原创粉丝点击