Largest Rectangle in a Histogram

来源:互联网 发布:一键复制淘宝别人宝贝 编辑:程序博客网 时间:2024/05/21 17:08

Largest Rectangle in a Histogram

Time Limit : 2000/1000ms (Java/Other)   Memory Limit : 131072/65536K (Java/Other)
Total Submission(s) : 61   Accepted Submission(s) : 28
Problem 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 integern, denoting the number of rectangles it is composed of. You may assume that1<=n<=100000. Then follow n integers h1,...,hn, where0<=hi<=1000000000. These numbers denote the heights of the rectangles of the histogram in left-to-right order. The width of each rectangle is1. 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
暴力搜索每个高度的左右边界,或者单调栈,单调栈暂时还没有实现;
l[i]=l[l[i]-1];据说这个公式会让移动变得更快,还有一个边界为0的陷阱;
而且右边界要从右边向左搜索,我也不知道为什么,老师说是数据问题;
#include <stdio.h>#include <stdlib.h>int l[100005],r[100005],n,i;long long h[100005];int main(){    while(scanf("%d",&n)&&n)    {        for(i=1; i<=n; i++)        {            scanf("%lld",&h[i]);            l[i]=i;            r[i]=i;        }        h[0]=-1;        h[n+1]=-1;        for(i=1; i<=n; i++)        {            while(l[i]>0&&h[l[i]-1]>=h[i])            {                l[i]=l[l[i]-1];            }        }        for(i=n; i>0; i--)        {            while(r[i]<=n&&h[r[i]+1]>=h[i])            {                r[i]=r[r[i]+1];            }        }        long long temp,max=0;        for(i=1; i<=n; i++)        {            temp=h[i]*(r[i]-l[i]+1);            if(max<temp)            {                max=temp;            }        }        printf("%lld\n",max);    }    return 0;}
0 0
原创粉丝点击