Largest Rectangle in a Histogram - HDU 1506 dp

来源:互联网 发布:canbot 软件 编辑:程序博客网 时间:2024/05/20 12:21

Largest Rectangle in a Histogram

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 10840    Accepted Submission(s): 2960


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 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
 
 

题意:找最大的矩形大小。

思路:l[i],r[i]表示以这个区间内的高度都不小于第i个的高度。

AC代码如下:

#include<cstdio>#include<cstring>#include<iostream>#include<algorithm>#include<cmath>typedef long long ll;using namespace std;ll value[100010],ans;int l[100010],r[100010];int main(){ int n,i,j,k;  while(~scanf("%d",&n) && n)  { for(i=1;i<=n;i++)    { scanf("%I64d",&value[i]);      l[i]=i;      r[i]=i;    }    value[0]=-1;    value[n+1]=-1;    for(i=1;i<=n;i++)     while(value[l[i]-1]>=value[i])      l[i]=l[l[i]-1];    for(i=n;i>=1;i--)     while(value[r[i]+1]>=value[i])      r[i]=r[r[i]+1];    ans=-1;    for(i=1;i<=n;i++)     ans=max(ans,value[i]*(r[i]-l[i]+1));    printf("%I64d\n",ans);  }}


0 0